php - 在 Laravel Eloquent 中更新一对多关系

标签 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();
            }
        }
    }

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

<?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-loading

关于php - 在 Laravel Eloquent 中更新一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29463624/

相关文章:

php - 我如何获得通过与 Laravel 5/Eloquent 的两个多对多关系关联的不同类别列表?

javascript - PHP生成jQuery——效率

php - 如何将 foreach 放入单独的变量中?

php - Laravel 中的可扩展模型

mysql - Laravel Eloquent : Alphabetical Order but from Small words to Sentence

laravel - 在没有 Controller 的情况下使用 Blade 内的查询功能

php - Codeigniter insert_batch 限制问题

php - 多维导航阵列

centos - laravel - 无法在服务器上打开 paths.php

php - 如何在 Laravel 4 中创建 Hstore 列类型?