[英]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之后強制更新此關系的數據的最佳做法是什么?
你有這個問題,因為使用查詢生成器而不是雄辯,我不明白為什么你使用兩者,如果你使用eloquent然后使用eloquent如果你使用查詢生成器使用查詢生成器,但不要使用兩者,至少不當你有可能不這樣做的時候。
我發現setConfigItem
方法沒用,因為你沒有將用戶推入設置但是設置為用戶,因此基本上所有實現應該在用戶類而不是在設置類上
清理完之后,你可以嘗試做這樣的事情 -
public function settingSet($key, $value)
{
$setting = new Setting([
'setting_key' => $key,
'setting_value' => $value
]);
$this->settings()->save($setting);
}
您也可以改進此方法,而不是一次只接受1個設置,您可以接受一系列設置
順便問一下你有沒有使用數據透視表的原因? 是設置獨特的foreach用戶?
您可以使用Lazy Eager Loading
, load()
函數強制更新數據。
print_r($user->load('settings'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.