Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

如何在Magento2 中使用 insertOnDuplicate 查询

使用 Magento 2 使用insertOnDuplicate查询,您需要先创建一个 Connection 对象才能使用 ResourceConnection 类运行查询。

当您将任何新行插入表中时,如果该行导致主键或唯一索引中的重复,则在 MySQL 中引发错误。

基本功能定义:

/**
 * Inserts a table row with specified data.
 *
 * @param mixed $table The table to insert data into.
 * @param array $data Column-value pairs or array of column-value pairs.
 * @param array $fields update fields pairs or values
 * @return int The number of affected rows.
 */
public function insertOnDuplicate($table, array $data, array $fields = []);

Example,

<?php
class Magento2Sql
{
 public function __construct(
     \Magento\Framework\App\ResourceConnection $resource
 ) {
     $this->resource = $resource;
 }

 public function executeInsertOnDuplicate()
 {
     $tableName = "Your_Tablename";
     $data = ["column_name1"=>"value1","column_name2"=>"value2"]; // Key_Value Pair
     $connection = $this->resource->getConnection();
     $connection->insertOnDuplicate($tableName, $data);
 }
}

第一个参数是 tableName
第二个参数是数组的键值对。
第三个参数对于表的数组字段是可选的。(更新字段对)

相关文章

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