Sometimes we need to perform a quick bulk update of a specific product attribute for the whole catalog. But as we know, fetching the whole Product entity takes a lot of resources.
So in this tutorial I will show you how to update a single product attribute value without loading the whole Product object.
In this standalone script, which can be placed on the project root and executed as php -f update-attr.php
, I’ll show you how to update the attribute “has_upload_file” for all of the products.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php use Magento\Framework\App\Bootstrap; require __DIR__ . '/app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $obj = $bootstrap->getObjectManager(); // Set the state. You can also set "adminhtml" $state = $obj->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); // Get the first product of a collection $products = $obj->get('Magento\Catalog\Model\ResourceModel\Product\Collection'); foreach ($products as $p) { $p->setData('has_upload_file', 0); $p->getResource()->saveAttribute($p, 'has_upload_file'); } |