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;
}
New relational model data of new value
Old relational model data saved.
| Q | A
| ---------------- | ---
| Yii version | 2.0.11.2
| PHP version | 5.6.29-0+deb8u1
| Operating system | GNU\Linux - Debian
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.
somewhat related https://github.com/yiisoft/yii2/issues/12749#issuecomment-254182125
@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 ;(((
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.