如何使用Magento2 创建Mysql更新查询?

您可以使用 Magento 2 和 Magento 方式创建更新查询。

您可以在 ResouceModel PHP 文件中编写自定义更新 MySQL 查询。

当您编写任何自定义更新查询时,您需要在 ResourceModel 文件夹 PHP 文件中创建一个函数。

基本定义:

/**
 * Updates table rows with specified data based on a WHERE clause.
 *
 * @param  mixed $table The table to update.
 * @param  array $bind Column-value pairs.
 * @param  mixed $where UPDATE WHERE clause(s).
 * @return int  The number of affected rows.
 */
public function update($table, array $bind, $where = '');

You can use direct SQL query for the update,

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

   /**
    * Update Sql Query
    */
   public function runUpdateQuery()
   {
       $connection  = $this->resource->getConnection();
       $data = ["key1"=>"value1","key2"=>"value2"]; // Key_Value Pair
       $id = 10;
       $where = ['entity_id = ?' => (int)$id];

       $tableName = $connection->getTableName("Your_Tablename");
       $connection->update($tableName, $data, $where);
   }
}

您可以像上面那样创建更新查询,
第一个参数是表名。
第二个参数是数组的键值对,用于更新现有表中的值。
第三个参数是 where 条件,您需要使用 where 条件更新特定记录。

$id = 1;
$productIds = [1,2,3,4,5];
使用单个 where 条件,
$where = ['entity_id = ?' => (int)$id]; 其签入查询,其中 entity_id = 1;

使用多个 where 条件,
$where = ['is_enable = ?' => (int)$id, 'product_id IN (?)' => $productIds];

上面的查询运行更新查询,其中 is_enable = 1 和 product_id 在 [1,2,3,4,5];

赞(0)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

版权属于: sbboke版权所有。

转载时必须以链接形式注明作者和原始出处及本声明。

张贴在magento2教程标签:

相关文章

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