Shamnad
Shamnad

Reputation: 35

How to use replace query in yii2 updateAll()?

I am using Postgresql. My Yii2 code for the update is

 ModelName::updateAll(['my_column' => "REPLACE(my_column1,'removed_','')"]);

Actual query is

update my_table set my_column = REPLACE(my_column1,'removed_','');

When I run my yii2 code it shows the error

SQLSTATE[22001]: String data, right truncated: 7 ERROR: value too long for type character varying(50) The SQL being executed was: UPDATE "my_table" SET "my_column1"='REPLACE(my_column1,''removed_'','''')'

Upvotes: 1

Views: 409

Answers (1)

Michal Hynčica
Michal Hynčica

Reputation: 6144

If you use ['column' => 'value'] syntax for attributes the framework expects that values of array are simple values and treats them accordingly. That's why your expression gets converted to string value instead of using as expression.

If you want to avoid that you need to wrap your values in yii\db\Expression like this:

 ModelName::updateAll([
    'my_column' => new \yii\db\Expression("REPLACE(my_column1,'removed_','')")
]);

Upvotes: 1

Related Questions