[英]Eloquent Update with One-to-One relationship
我想使用Eloquent模型更新數據庫中的記錄。 我在更新user_profile
表時出錯,說where id is not null
。
用戶模型
class User extends Model
{
public function profile()
{
return $this->hasOne('App\Models\Common\UserProfile');
}
}
UserProfile模型
class UserProfile extends Model
{
public function user()
{
return $this->belongsTo('\App\Models\User');
}
}
調節器
$user->fill($data);
$user->save();
$user->profile->fill($data);
$user->profile->save();
在MySQL查詢中,它看起來像這樣:
UPDATE users, user_profiles
SET users.name='Test Name',
user_profiles.email='test@gmail.com'
WHERE users.id=1
AND user_profiles.user_id=1;
我知道MySQL查詢,但是我是Eloquent
新手,我想在Eloquent model
。 也許這里有些可以解釋魔術在《 Eloquent
工作原理。
默認情況下,雄辯地假設任何模型都有一個id
列作為主鍵。 如果不是這種情況,則需要使用以下命令“注冊”主鍵
protected $primaryKey = 'user_id';
在模型類中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.