Вопрос

I created a new table company_shipping_quote.

I am writing data into it like this:

$quoteId = $quote->getId();
$html = $this->_generateNote($expressRule);

$quoteModel = $this->_companyShippingQuoteFactory->create();
$quoteModel->setQuoteId($quote->getId());
$quoteModel->setExpressNote($html);
$quoteModel->save();

But this does not check if there is already an entry with the value for quote_id and it just creates duplicates.

enter image description here

How can I check if there is already a row with that quote_id before creating it?

Это было полезно?

Решение

try below code - Another way

<?php

protected $_companyShippingQuoteFactory;

public function __construct(
    ...
    \Company\Shipping\Model\QuoteFactory $companyShippingQuoteFactory
) {
    ...
    $this->_companyShippingQuoteFactory = $companyShippingQuoteFactory;
}

...

$quote_id =13718;

$quoteModel = $this->_companyShippingQuoteFactory->create();
$quoteModel->load($quote_id, 'quote_id');
if ($quoteModel->getId()) {
    echo "Updated";
} else {
   echo "New Added";
}
$quoteModel->save();

Другие советы

Try This Code

protected $_companyShippingQuoteFactory;

public function __construct(
    ...
    \Company\Shipping\Model\Quote\ResourceModel\CollectionFactory $companyShippingQuoteFactory
) {
    ...
    $this->_companyShippingQuoteFactory = $companyShippingQuoteFactory;
}

...

$quote_id =13718;

$quoteModel = $this->_companyShippingQuoteFactory->create();
$quoteModel->addFieldToFilter('quote_id',$quote_id)

if(count($quoteModel->getData())){
    echo "quote id added";
} else {
    echo "New quote id";
}

There might be a more straight forward solution.

If quote_id is unique in your database it makes more sense to use it as a primary key.

So you remove entity_id from db_schema.xml and change the resourceModel accordingly changing _idFieldName to quote_id. You then add this to the _construct(): (check this question how to save data into custom table):

$this->_isPkAutoIncrement = false;

Of your resource model, you then be able to change the value by code like this assuming the quoteId already exists in the database:

$quoteModel = $this->_companyShippingQuoteFactory->create();
$quoteModel->setQuoteId($quote->getId());
$quoteModel->setExpressNote($newHTMLhtml);
$quoteModel->save();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top