When I save Product in shell(foreach loop) like below, the product image roles will disappear!

$product = $this->productRepository->getById($data['product_id']);

I google it and found it is a official bug and not fixed yet(include version 2.1, 2.2, 2.3). The official github issue link is Product image roles randomly disappear. The codes below will lost all image roles too.

$store = $this->storeManager->getStore(0);
$product = $this->productRepository->getById($data['product_id'], true, $store->getId());

It seems as long as we use $this->productRepository->save($product);, it will lost product image roles.

How to temporarily solve the problem before the official fix the bug?


I found a solution in github $product->unsetData('media_gallery'); $this->productRepository->save($product);, but it will make a critical error on the catalog_product_view page.

After research the productRepository codes, I came up with two temporary solution by myself. The problem cost my several hours, hope the solution will help others too.

After my test, the solutions work in version 2.2.3. Other version should work too.

1. If you did not lost your image roles yet

Save the product by productRepository like below:

$product = $this->productRepository->getById($data['product_id']);

2. If you already lost your image roles

If you already lost your image roles just like me T^T, you have to assign the image roles to products by custom shell or controller.

After get the product ids you want, for each product write the codes like below

$product = $this->productRepository->getById($data['product_id']);
$mediaGalleryEntriesTemp = [];
$i = 1;
foreach ($product->getMediaGalleryEntries() as $item) {
    if ($i === 1) {
        $item->setTypes(['image', 'small_image', 'thumbnail']);
    $mediaGalleryEntriesTemp[] = $item;

Notice: 'swatch_image' role only available in simple product or configurable child product, not configurable parent product.

If someone has better solution, your post is welcome :)

Or the official fix the bug, please let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.