使用Join进行Yii2 QueryBuilder更新

时间:2015-02-21 20:52:17

标签: php mysql yii2

我有以下原始SQL查询:

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。

如何将此原始SQL查询“转换”为Yii2 QueryBuilder?

[UPDATE]

正如Felipe所说,查询构建器不可能这样,所以我最终按照以下方式执行:

    $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();

1 个答案:

答案 0 :(得分:2)

我担心Yii 2 Query Builder仅适用于选择查询

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

  • 原始SQL:

    \Yii::$app->db->createCommand('update user set status = 1 where age > 30')->execute();
    
  • 带有占位符的原始SQL(防止SQL注入)

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

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

更多信息: