在Laravel's Eloquent中更新一对多关系

gpm*_*dam 7 php laravel eloquent laravel-5

假设我在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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想要检索单个用户及其设置,我可以执行以下操作:

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

现在,有了这个用户,我可以使用settingSet上面列出的方法更新或插入设置.

<?php
$user->settingSet('foo','bar');
Run Code Online (Sandbox Code Playgroud)

但是,如果我此时检索设置,我将获得过时的数据.

<?php
print_r($user->settings); // onoes!
Run Code Online (Sandbox Code Playgroud)

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

min*_*noz 1

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

print_r($user->load('settings'));
Run Code Online (Sandbox Code Playgroud)

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