Reading list Switch to dark mode

    Magento2 mass update records without loading model

    Updated 4 March 2024

    Magento2 mass update records without loading model – As developer many times we needs to update table records in a bulk.

    For example changing status (mass action). For this approach if you will get collection factory and save records inside foreach then it’s a bad practice.

    Because each time inside the loop when you are saving the record a query is getting fired on the database. This is likely to consume more time and memory and can result in delay in updation when the number of records are higher.

    So here is the solution to update records without saving inside foreach by following some easy steps given below :

    To Update the values in bulk using a collection, please follow the steps below :

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    First of all create model resource model and collection for the table in which you want to update the records in bulk.

    1. Write update records method in your model collection file. Like if you want to upgrade “status” column value in your “custom_records” table, so you will need to write these methods in your collection model path will be like – magento_root/app/code/Webkul/Custom/Model/ResourceModel/CustomRecords/Collection.php
    <?php
    
    namespace Webkul\Custom\Model\ResourceModel\CustomRecords;
    
    use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
    
    /**  * Webkul Custom ResourceModel CustomRecords collection  */
    class Collection extends AbstractCollection
    {
        /**
         * @var \Magento\Store\Model\StoreManagerInterface
         */
        protected $storeManager;
        /**      
         * @param \Magento\Framework\Data\Collection\EntityFactoryInterface     $entityFactory
         * @param \Psr\Log\LoggerInterface                                      $logger  
         * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface  $fetchStrategy
         * @param \Magento\Framework\Event\ManagerInterface                     $eventManager      
         * @param \Magento\Store\Model\StoreManagerInterface                    $storeManager      
         * @param \Magento\Framework\DB\Adapter\AdapterInterface|null           $connection      
         * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb|null     $resource      
         */     public function __construct(
            \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
            \Psr\Log\LoggerInterface $logger,
            \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
            \Magento\Framework\Event\ManagerInterface $eventManager,
            \Magento\Store\Model\StoreManagerInterface $storeManager,
            \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
            \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
        ) {
            parent::__construct(
                $entityFactory,
                $logger,
                $fetchStrategy,
                $eventManager,
                $connection,
                $resource
            );
            $this->storeManager = $storeManager;
        }
        /**
         * @var string
         */
        protected $_idFieldName = 'entity_id';
    
        /**      
         * Define resource model
         *     
         * @return void      
         */
        protected function _construct()
        {
            $this->_init('Webkul\Custom\Model\CustomRecords', 'Webkul\Custom\Model\ResourceModel\CustomRecords');
            $this->_map['fields']['entity_id'] = 'main_table.entity_id';
        }
        /**
         * Update Data for given condition for collection
         * 
         * @param int|string $limit      
         * @param int|string $offset
         * @return array      
         */
        public function setTableRecords($condition, $columnData)
        {
            return $this->getConnection()->update($this->getTable('custom_records'), $columnData, $where = $condition);
        }
    }

    2. Now inside your controller create a collection factory and call setTableRecords() method with parameters as explained above –

    <pre class="brush:php">$condition = "`entity_id`= 1 OR `entity_id`= 2"; //any record id with OR operator $status = 1; $this->_objectManager->create(     'Webkul\Custom\Model\CustomRecords' )->getCollection() ->setTableRecords(     $condition, ['status' => $status] );</pre>

    I fetched table collection using object manager to explain it in easy way but you should use collection factory pattern to get the collection for code efficiency as using object manager is already deprecated in latest versions of Magento.

      So in this way you can update any column records without loading collection for each record.

      Magento2 mass update records without loading model

      You can also check :

      . . .

      Leave a Comment

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


      1 comments

    1. Tomas Jindal
    2. Back to Top

      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home