QueryBuilder更新并加入

QueryBuilder更新并加入

本文介绍了Yii2 QueryBuilder更新并加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下原始SQL查询:

I have the following raw SQL query:

UPDATE `pay_audit`
JOIN `invoice_items`
ON `invoice_items`.`mdn` = `pay_audit`.`account_id`
AND `invoice_items`.`unitprice` = `pay_audit`.`payment`
AND `invoice_items`.`producttype_name` LIKE 'PAYMENT'
AND DATE_FORMAT(`invoice_items`.`created`, '%Y-%m-%d') = '2015-02-21'
SET `pay_audit`.`invoice_item_id` = `invoice_items`.`id`
WHERE `pay_audit`.`report_date` = '2015-02-21'

日期是php中的$ date变量.

The date is a variable $date in php.

如何将这个原始SQL查询转换"为Yii2 QueryBuilder?

How can i "convert" this raw SQL query into Yii2 QueryBuilder?

[更新]

正如Felipe提到的那样,查询生成器是不可能的,所以我最终按照以下步骤进行操作:

As Felipe mentioned it's not possible with query builder so i ended up doing it like followed:

    $today = date('Y-m-d');
    $sql = "";
    $sql .= "UPDATE `pay_audit` ";
    $sql .= "JOIN `invoice_items` ";
    $sql .= "ON `invoice_items`.`mdn` = `pay_audit`.`account_id` ";
    $sql .= "AND `invoice_items`.`unitprice` = `qpay_audit`.`payment` ";
    $sql .= "AND `invoice_items`.`producttype_name` LIKE 'PAYMENT' ";
    $sql .= "AND DATE_FORMAT(`invoice_items`.`created`, '%Y-%m-%d') = '$today' ";
    $sql .= "SET `pay_audit`.`invoice_item_id` = `invoice_items`.`id` ";
    $sql .= "WHERE `pay_audit`.`report_date` = '$today'";

    $command = \Yii::$app->db->createCommand($sql);
    $command->execute();

推荐答案

恐怕 Yii 2查询生成器仅用于选择查询.

对于更新查询,您至少具有三个选项:

For update queries you have at least three options:

  • 原始SQL:

  • Raw SQL:

\Yii::$app->db->createCommand('update user set status = 1 where age > 30')->execute();

  • 带有占位符的原始SQL(以防止SQL注入)

  • Raw SQL with placeholders (to prevent SQL injection)

    \Yii::$app->db->createCommand('update user set status = :status where age > 30')->bindValue(':status','1')->execute();
    

  • update()方法

  • update() method

    // update user set status = 1 where age > 30
    \Yii::$app->db->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
    

  • 更多信息在这里:

    有关SO的另一个问题

    这篇关于Yii2 QueryBuilder更新并加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    09-05 03:05