假設我有以下兩種模式之間的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