AR SET VALUE AS QUERY/EXPRESSION

I have a problem setting value in AR.

Is it possible to update a column using query ?

I tried something like:




 $model = Model::findOne(1);

 $model->amount = Model2::find()->select(new Expression('sum(amount)'))

 $model->save()



I also tried this:




 $mode->amount = new Expression(Model2::find()->select(new Expression('sum(amount)')))



Is this possible ? Because it doesn’t work on me.

It says

If this is possible, can someone please tell me how.

Thank you

It returns an object of type yii\db\ActiveQuery - what’s the problem ?

The problem is I want to set the value of the model as summation of other tables column.

I can do:




 // select sum(amount) from table2

 $amount = Model2::find()->sum('amount');


 // update table1 set amount = 42

 $model = Model::findOne(1);

 $model->amount = $amount;

 $model->save();



But i don’t want to execute 2 queries if I can just do one with subquery




 // update table1 set amount = (select sum(amount) from table2)

 $model = Model::findOne(1);

 $model->amount = Model2::find()->select('sum(amount)');

 $model->save();



Thank you

It’s not a kind of thing that AR is designed for.

If you really need to have the maximum speed to update db records, you’d better use a raw sql.