Reputation: 2987
I have this situation:
1 .$model = Model::where(someCondition);
After that code above I do some updates to $model child relationship, model has settings relationship so I update them and save them to db.
Then I try later to access $model->settings and I only get the settings that where there when I did (1) above and not all the settings that i just added and saved to db.
I find my self having to after doing some updates to settings, to do this again so it loads the new settings that have been added to db table.
so I repeat this line $model = Model::where(someCondition);
to be able to do this $model->settings and get fresh data from db.
Is this how it has to be done or is there a way to refresh relationship so it gets latest data from db instead of using data from when I first created the model?
Hope you understand what I mean.
here is some code:
$tBlock = TemplateBlock::set($template_id, $blockData, $parentId);
// remove settings from db that have default values
foreach ($tBlock->getSettingsNoDefaults() as $baseKey => $value) {
if(!array_key_exists($baseKey, $blockData->settings)) {
$tBlock->removeSetting($baseKey);
}
}
// only save settings that have been customized by user
foreach ($blockData->settings as $key => $setting) {
$tBlock->setSetting($key, $setting['value'], $setting['type']);
}
// refresh the block so we get latest settings
$tBlock = TemplateBlock::where('tblock_id', $template_id);
$settings = $tBlock->settings;
setSetting function looks like:
public function setSetting($key, $value, $type = 'string')
{
$setting = $this->settings()->updateOrCreate(
['key' => $key],
['key' => $key, 'value' => $value, 'type' => $type]
);
return true;
}
notice i have to get tBlock again by doing:
$tBlock = TemplateBlock::where('tblock_id', $template_id);
that gives me what I am after, but it feels so not elegant, is there a better way?
Upvotes: 3
Views: 2628
Reputation: 50531
$model->load('relationship')
will lazy eager load the relationship anew.
Docs 5.4 - Eloquent - Relationships - Eager loading
Upvotes: 3