Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: update field with query builder

How can I update field with query builder in Yii2? I can't find this in documentation.

Thanks!

UPD

This is the solution:

// UPDATE $connection = Yii::$app->db; $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute(); 
like image 929
arfname Avatar asked Aug 24 '14 07:08

arfname


People also ask

How to write update query in Yii2?

Like other answers have pointed out, you can call update() on the builder object. Yii::$app->db->createCommand()->update('tableName', ['field' => 'value'], condition)->execute() . The 2nd parameter is a key-value pair of the fields you want to set and the values you want to set them to.

What is Query Builder?

Using Query Builder, you can search and filter database objects, select objects and columns, create relationships between objects, view formatted query results, and save queries with little or no SQL knowledge.


2 Answers

Create command can be used directly as follows :

\Yii::$app->db->createCommand("UPDATE table SET column1=:column1, column2=:column2 WHERE id=:id") ->bindValue(':id', your_id) ->bindValue(':column1', :column1_value) ->bindValue(':column2', :column2_value) ->execute(); 
like image 114
Kshitiz Avatar answered Oct 06 '22 02:10

Kshitiz


Query builder is for select queries only (sum, max, count too). You should use other methods - AR or raw queries (https://github.com/yiisoft/yii2/blob/master/docs/guide/db-dao.md#basic-sql-queries)

like image 22
zelenin Avatar answered Oct 06 '22 03:10

zelenin