假设我有以下两种模式之间的Laravel雄辩的关系:更新在Laravel雄辩的一到多的关系
<?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!
什么给力的数据,这种关系的INSERT/UPDATE后进行更新/删除User::settingSet
方法或其他类似方法,最好的做法?
你确定你是在救你$用户> settingSet($键,$值)中设定的设置? – martindilling 2015-04-07 09:31:37
@martindilling是的,下一页刷新显示新值。 – gpmcadam 2015-04-10 16:20:04
你可以显示'settingSet'方法吗? – Gal 2015-04-10 16:48:53