如何以magento 2格式编写mysql更新查询?

ResourceModel模型中,我需要执行更新查询。

$ sql =“ UPDATE 2067_ci_sessions SET data ='$ cisess_data'WHERE id = $ id”;

而不是编写直接的mysql查询,我如何以magento 2格式编写更新查询?

根据Github属于Marius的说法,这是SQL方式:

$this->getConnection()->update(
    $object->getResource()->getTableName($table),
    $cisess_data,
    ['id = ?' => (int)$cisess_cookie]
);

或者

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('employee'); //gives table name with 
 prefix
//Update Data into table
$sql = "Update " . $tableName . "Set emp_salary = 20000 where emp_id = 12";
$connection->query($sql);

或者

对于单个记录

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('custom_table'); //gives table name with 
 prefix
//Update Data into table
$sql = "Update " . $tableName . "Set qty = '123' where id = '2'";
$connection->query($sql);

对于多个记录

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();

$updateData = [1 => 7, 2 =>15, 3 => 19, 4=>3];
$insertData = [];
foreach($updateData as $id => $qty) {
$insertData[] = ['id' => $id, 'qty' => $qty];
}
try {
    $connection->beginTransaction();
    $connection->insertMultiple($this->getTable('custom_table'), $insertData);
    $connection->commit();
} catch(\Exception $e) {
    $connection->rollBack();
}

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
最旧
最新 最多投票
内联反馈
查看所有评论