How to save multiple products faster way in Magento 2 - Magesan

How to save multiple products faster way in Magento 2

How to save multiple products faster way in Magento 2

Sometimes when we are working on some projects we need to update a single product attribute, but when it times to update on multiple products, possibly even hundreds of them.

You might get a PHP timeout error OR MySQL error will thrown in log.

In below example I will tell you how you can update multiple products with faster way and even a better way.

Create a file at Magesan/Extension/Model/UpdateProductManagement.php

In UpdateProductManagement.php have the code :

<?php
 
namespace Magesan\Extension\Model;
 
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\ResourceModel\Product as ProductResource;
 
class UpdateProductManagement
{
    const ASSIGNED_CUSTOMER = "assigned_customer";
 
    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;
 
    /**
     * @var ProductResource
     */
    protected $productResource;
 
    /**
     * __construct
     *
     * @param ProductRepositoryInterface $productRepository
     * @param ProductResource $productResource=
     */
    public function __construct(
        ProductRepositoryInterface $productRepository,
        ProductResource $productResource
    ) {
        $this->productRepository = $productRepository;
        $this->productResource   = $productResource;
    }
 
    public function updateProducts($customerId, $skus)
    {
        try {
            foreach ($skus as $sku) {
                $product = $this->productRepository->get($sku); // loading product via provided multiple skus array
 
                $product->setAssignedCustomer($customerId); // product attribute name is assigned_customer
                $this->productResource->saveAttribute($product, self::ASSIGNED_CUSTOMER); // this code responsible for updating faster.
            }
 
            return "Products Updated Successfully";
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), 1);
        }
    }
}

That’s it, You are good to go now.

But keep in mind that when using this approach. The assigned_customer attribute is going to save for such a fast way but all the events that are usually run when saving the whole product are not fired in this scenario. So if you have some observers created to these events, then these observers will going to execute.

Else everything will work in such a faster way.

Happy Coding…

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>