我有两个模型'用户'和'配置文件'。Laravel - 更新OneToOne关系
'email'字段位于User模型中,而'name'字段位于Profile模型中。
'profiles'表具有'user_id'的外键。
我搜索了很多,但无法找到一个适当的解决方案,我怎样才能一次更新这两个实体。
在我的ProfileController中,我正在这样做,但我确信有更好的方法。请帮忙。
public function update($id)
{
$profile = Profile::where('id', $id);
$profile->name = 'Jon';
$profile->save();
$user = User::where('id', $profile->user_id);
$user->email = '[email protected]';
$user->save();
}
我的个人资料模型
public function user()
{
return $this->belongsTo('User');
}
我的用户模型具有
public function profile()
{
return $this->hasOne('Profile');
}
那么你可以使用数据库触发器。 – 2014-09-19 10:06:34
如果配置文件与用户具有hasOne关系,并且您已经找到配置文件,则可以通过$ profile-> user获取用户;从哪个角度讲,可以节省您另一个SQL查询。 – Adimeus 2014-09-19 10:07:31
另一件事是一对一的关系在分开的表格中没有多大意义。 – 2014-09-19 10:12:53