Magento 2 - update single model value

December 17, 2020

Magento 2: update single model value (field) without loading the whole model instance

Programing is about thinking, not writing Photo by olia danilevich from Pexels

Well, let's say we're in above situation, and it's not applicable in our case to use the classic method where we can just use setter to set the value we want and then just persist these changes to the database.

So what shall we do in such case?

For me the best solution so far is to use Magento 2 App Resource instance with which you can update one or more model fields (attributes) manually - it's like you're running single SQL update statement for one table.

So the easiest way and most-common - also recommended, is to inject the instance of class Magento\Framework\App\ResourceConnection into construct - don't use ObjectManager just to get the instance - it's not recommended by Magento standards, and then perform the action either in some function or wrote own function and call it on place you need it.

use Magento\Framework\App\ResourceConnection;
use Psr\Log\LoggerInterface;

/** 
 * @var ResourceConnection $connection 
 */
protected $connection;

/** 
 * @var LoggerInterface $logger 
 */
protected $logger;

/**
 * @param ResourceConnection $connection
 * @param LoggerInterface $logger
 */
public function __construct(
    ResourceConnection $connection, 
    LoggerInterface $logger
){
    $this->connection = $connection;
    $this->logger = $logger;
}

/**
 * @param $itemId
 * @param $status
 */
protected function updateItemStatus(int $itemId, $status): void
{
    try {
        $this->connection->getConnection()->update('sales_order_item', [
            'my_custom_product_status' => $status,
        ],
            $this->connection->getConnection()->quoteInto('item_id = ?', $itemId)
        );
    } catch (Exception $exception) {
        $this->logger->error($exception->getMessage());
    }
}

This way we can easily update, in our case model Sales_order_item, attribute on some model without the need to use repository or factory to load the whole model with all attributes when we have to update only one single attribute.

I hope this will help you and you'll find it useful!

Join the Newsletter

Subscribe to get our latest content by email.

    We won't send you spam. Unsubscribe at any time.

    Join the Newsletter

    Subscribe to get our latest content by email.
      We respect your privacy. Unsubscribe at any time.