Updating a One-To-Many Relationship in Laravel's Eloquen


Updating a One-To-Many Relationship in Laravel's Eloquent

假设我在Laravel的Eloquent中有以下两个模型之间的关系:

<?php
    // user:
    // - user_id
    class User extends Model
    {
        protected $table = 'users';
        public function settings()
        {
            return $this->hasMany('Setting');
        }
        public function settingSet($key, $value)
        {
            'Setting::setConfigItem($key, $value, $this->user_id);
        }
    }
    // settting:
    // - setting_key
    // - setting_value
    // - user_id
    class Setting extends Model
    {
        public function setConfigItem($key, $value, $user_id)
        {
            // Note: I've provided this code here as an example, so it should
            // exist here only as pseudo-code - it has not been tested and
            // is outside the scope of this issue but has been requested by 
            // a commenter so I've provided the basis for this method:
            $existing = 'Setting::where(['key' => $key, 'user_id' => $user_id])->first();
            if (!$existing) {
                'Setting::insert([ 'setting_key' => $key, 'setting_value' => $value, 'user_id' => $user_id ]);
            } else {
                $existing->setting_value = $value;
                $existing->save();
            }
        }
    }

并且我想检索单个用户和他的设置,我可以做以下操作:

<?php
$user = User::with(['setting'])->find(1);

现在,有了这个用户,我可以使用settingSet方法更新或插入设置,如上所述。

<?php
$user->settingSet('foo','bar');

但是,如果我在此时检索设置,我将得到过时的数据。

<?php
print_r($user->settings); // onoes!

User::settingSet方法或其他类似方法中的INSERT/UPDATE/DELETE之后,强制更新此关系的数据的最佳做法是什么?

您可以使用Lazy Eager Loadingload()函数强制更新数据。

print_r($user->load('settings'));

来源:http://laravel.com/docs/5.0/eloquent#eager-加载

你有这个问题是因为使用了查询生成器而不是雄辩器,我不明白你为什么同时使用这两种方法,如果你使用的是雄辩器,那么使用雄辩器如果你使用查询生成器,那么使用查询生成器。使用查询生成器吧,但不要同时使用这两者,至少在你有可能不使用的情况下不要这样做。

我发现setConfigItem方法没有用,因为你不是把用户推到设置中,而是把设置推到用户中,所以基本上所有的实现都应该在用户类上,而不是在设置类上

清除后,你可以尝试做这样的事情-

public function settingSet($key, $value)
{
    $setting = new Setting([
        'setting_key' => $key,
        'setting_value' => $value
    ]);
    $this->settings()->save($setting);
}

你也可以改进这种方法,而不是一次只接受一个设置,你可以接受的设置数组

顺便问一句,你不使用透视表是有原因的吗?每个用户的设置是唯一的吗?