0

I want to do bulk insert and update to my custom model collection, right now I can only do insert multiple records to DB like this:

public function __construct( 
    \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor,
    \Magento\Framework\App\ResourceConnection $resource
) { 
    $this->connection = $resource->getConnection();
    $this->resource = $resource; 
}

public function execute(){
  $data[]['name'] = 'Bond'
  $data[]['code'] = '007';
  $data[]['name'] = 'Lancelot';
  $data[]['code'] = '002';
  $this->connection->insertMultiple($this->resource->getTableName('agent'), $data);
}

this will add those 2 data records to my database table agent, the problem is when I execute this multiple time it will insert new data, I want to update the data if the code column is same

4
  • code is your primary column into the table, right? Mar 9, 2020 at 11:01
  • yes looks like 'code' is primary key of table. Mar 9, 2020 at 11:52
  • @DhirenVasoya code is not primary key, this table doesn't have primary key
    – jojo
    Mar 9, 2020 at 12:14
  • Then you need to set that one, and due to that reason you face the issue. Mar 9, 2020 at 12:17

1 Answer 1

1

Replace insertMultiple with insertOnDuplicate. Try this:

/**
 * @param \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor
 * @param ResourceConnection $resource
 */
public function __construct(
    \Magento\Framework\App\Request\DataPersistorInterface $dataPersistor,
    \Magento\Framework\App\ResourceConnection $resource
) {
    $this->connection = $resource->getConnection();
    $this->resource = $resource;
}

public function execute()
{
    $data[]['name'] = 'Bond';
    $data[]['code'] = '007';
    $data[]['name'] = 'Lancelot';
    $data[]['code'] = '002';
    $this->connection->insertOnDuplicate($this->resource->getTableName('agent'), $data);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.