刷新关系而无需重新加载模型 [英] refresh the relationship without reloading the model

查看:52
本文介绍了刷新关系而无需重新加载模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况:

1.$ model = Model :: where(someCondition);

1 .$model = Model::where(someCondition);

上面的代码之后,我对$ model子关系进行了一些更新,model具有设置关系,因此我将其更新并将其保存到db.

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.

然后,我稍后尝试访问$ model-> settings,我只获得上面(1)所做的设置,而不是我刚刚添加并保存到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.

所以我重复这一行$ model = Model :: where(someCondition);

so I repeat this line $model = Model::where(someCondition);

能够执行此$ model->设置并从db获取新数据.

to be able to do this $model->settings and get fresh data from db.

这是必须完成的吗,还是有一种刷新关系的方法,以便它从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.

下面是一些代码:

    $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函数如下:

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;
}

注意,我必须通过执行以下操作再次获得tBlock:

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?

推荐答案

$ model-> load('relationship')将懒惰地渴望重新加载关系.

$model->load('relationship') will lazy eager load the relationship anew.

文档5.4-雄辩-关系-渴望加载

这篇关于刷新关系而无需重新加载模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆