Yii2: afterSave dont refresh relational model

Created on 14 Feb 2017  路  9Comments  路  Source: yiisoft/yii2

What steps will reproduce the problem?

Relational model data dont refresh afterSave. If you customize the afterSave Model with a relational model, the first model stay last data save for example:

Appointment have realtion by dealer

public function getDealer()
{
      return $this->hasOne(Dealer::className(), ['id' => 'dealer_id']);
}

Dealer 1
name = Toyota

Dealer 2
name = Ford

````php

$model = Appointment->findOne($id);
//current dealer_id = 1

//update this dealer_id
$model->dealer_id = 2;
$model->save();

````

Aftersave model on Appointment send a email with $this var

php public function afterSave($insert, $changedAttributes) { parent::afterSave($insert, $changedAttributes); var_dump($this->dealer_id); //return 2 is ok var_dump($this->dealer->id); //return 1 is wrong var_dump($this->dealer->name); //return Toyota is wrong return true; }

What is the expected result?

New relational model data of new value

What do you get instead?

Old relational model data saved.

Additional info

| Q | A
| ---------------- | ---
| Yii version | 2.0.11.2
| PHP version | 5.6.29-0+deb8u1
| Operating system | GNU\Linux - Debian

enhancement

Most helpful comment

@samdark You won't need extra query since you don't need related object immediately. The solution could be just unsetting related object when FK field has changed - extra query would be executed only when user access relation again.

All 9 comments

Since you won't need related model immediately most of the time (in forms) AR is avoiding extra query to refresh data. You may trigger refresh by calling same-named method if you need it. This is by design.

@samdark You won't need extra query since you don't need related object immediately. The solution could be just unsetting related object when FK field has changed - extra query would be executed only when user access relation again.

Ah, right. That's an option.

@samdark What is status of this issue or How to resolve this issue?

Going to be fixed in 2.0.14.

I have shop with Order and OrderItem models.
With new order in controller I load data from $_POST, create relational OrderItem records and populate relation 'items' for validation and in-events processing purposes (for example warehouse module can check item quantity before order creating), and saving them in Order::afterSave.

Now in 2.0.14 after relation is flushed i have no data in Order::afterSave as models were new, my items are lost. What should i do?

You should create a separate issue :)

i'll do, but now i think it will be closed due contradiction with updated framework design, as it's been with this issue ;(((

Was this page helpful?
0 / 5 - 0 ratings