Reputation: 2143
I have a project in Yii2 where I have two models in a one-to-one relation.
The two models are Plan
and Subscription
, and each has a getSubscription
and getPlan
method respectively.
I am eager loading a large group of them by using with:
$plans = Plan::find()->with('subscription')->all();
However, I am modifying some of the Plan
s subscription_id
with:
$plan->subscription_id = 5;
$plan->save();
The problem is that now $plan->subscription
contains the original Subscription
, and not the Subscription
with the new id.
Is there a way to make Yii2 grab the new Subscription
, only after the id has been updated (and not lazy load all of the Subscription
s)?
Upvotes: 0
Views: 346
Reputation: 1677
If I do not misunderstand, you can do as this
<?php
use yii\db\ActiveRecord;
class Plan extends ActiveRecord
{
public function init()
{
$this->on(self::EVENT_AFTER_UPDATE, [$this, 'afterUpdateHandler']);
}
/**
* @param \yii\db\AfterSaveEvent $event
*/
public function afterUpdateHandler($event)
{
if (isset($event->changedAttributes['subscription_id']))
{
$this->subscription = NULL;
}
}
// ...
}
?>
Next time you call $plan->subscription
, the subscription
your Plan
associated with will be retrofitted.
Instead of implementing it as an event handler, you could also rewrite the
afterSave
method.
Upvotes: 1