Magento 2 Quote Table – Update Custom Column Data

custom-quotemagento-2.1quote

I inserted a custom column in quote table like this:

if (version_compare($context->getVersion(), '1.0.1', '<')) {
          $setup->getConnection()->addColumn(
              $setup->getTable('quote'),
              'custom_column',
              [
                  'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                  'nullable' => true,
                  'comment' => 'Custom Column',
             ]
          );
        }

The custom column was successfully created, and added to every single row in quote table with null value, but the problem is, i don't know how to update the custom column data in the quote table by using only quote id

Best Answer

The easiest way to solve this is to fill in this field in the quote model and save it using the Repository:

class QuoteUpdater
{
    /**
     * @var \Magento\Quote\Model\QuoteRepository
     */
    protected $quoteRepository;

    /**
     * @param \Magento\Quote\Model\QuoteRepository $quoteRepository
     */
    public function __construct(
        \Magento\Quote\Model\QuoteRepository $quoteRepository
    ) {
        $this->quoteRepository = $quoteRepository;
    }

    public function updateQuoteData($quoteId, int $customData)
    {
        $quote = $this->quoteRepository->get($quoteId); // Get quote by id
        $quote->setData('custom_column', $customData); // Fill data
        $this->quoteRepository->save($quote); // Save quote
    }
}
Related Topic