Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 QueryBuilder Update with Join

Tags:

php

mysql

yii2

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'

The date is a variable $date in php.

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

[UPDATE]

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();
like image 952
Andreas Hinderberger Avatar asked Feb 21 '15 20:02

Andreas Hinderberger


1 Answers

I'm afraid Yii 2 Query Builder is for select queries only.

For update queries you have at least three options:

  • Raw SQL:

    \Yii::$app->db->createCommand('update user set status = 1 where age > 30')->execute();
    
  • 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() method

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

More info here:

  • Yii DAO

  • Another question on SO

like image 116
Felipe Avatar answered Oct 16 '22 08:10

Felipe