Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update table column with another column values of the same table using updateAll()

Tags:

php

mysql

yii2

I have a table that contains these two real fields current and origin.

current value is updated regularly. I want to write a script of reset: for each row I want to put the origin value in the current value.

In MySQL it's possible with this query:

update MyTable set current = origin

I tried to write this in Yii2 with the query builder:

return $this->updateAll(['current' => 'origin']);

But this doesn't work because origin is interpreted as string and all rows updated with the value 0.

So how I can update field value by the value of another field using updateAll()?

like image 402
Touhami Avatar asked Feb 04 '15 18:02

Touhami


People also ask

How can we update one column value with another column in the same table?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.

How can I update two columns with same value in SQL?

To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.

How update a column value with another column in the same table in MySQL?

In MySQL, if you want to update a column with the value derived from some other column of the same table we can do so by using a SELF JOIN query and if you wish to modify the value derived from another column like maybe get a substring from the text or break the string using some delimiter, then we can use the ...

How can I update one table column from another table column in SQL Server?

UPDATE syntax:UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID. we can use the following command to create a database called geeks.


1 Answers

Wrap origin in yii\db\Expression like so:

use yii\db\Expression;

...

return $this->updateAll(['current' => new Expression('origin')]);

and result will be as expected.

like image 174
arogachev Avatar answered Sep 18 '22 04:09

arogachev