2014-09-19 65 views
0

我有两个模型'用户'和'配置文件'。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'); 
} 
+0

那么你可以使用数据库触发器。 – 2014-09-19 10:06:34

+0

如果配置文件与用户具有hasOne关系,并且您已经找到配置文件,则可以通过$ profile-> user获取用户;从哪个角度讲,可以节省您另一个SQL查询。 – Adimeus 2014-09-19 10:07:31

+0

另一件事是一对一的关系在分开的表格中没有多大意义。 – 2014-09-19 10:12:53

回答

4

你不能做到这一点一气呵成。

但是你可以把它简化一下,通过利用Laravel的功能,像这样(做它一走样的方式):

1控制器编辑

$profile = Profile::with('user')->find($id); 
// make sure you eager load the user for below to work 

2查看

{{ Form::model($profile) }} 
    {{ Form::text('name') }} 
    {{ Form::text('user[email]') }} 
{{ Form::close() }} 

这将自动填写您的个​​人资料数据(和用户数据太)

3控制器更新

$profile = Profile::find($id); 
$profile->fill(Input::only(.. fields you want to update ..)); 
$profile->user->fill(Input::get('user')); // array of user data form the form 
$profile->push(); // save both models in one go BUT separate queries 

另外,还要确保你有你的模型fillable,所以fill意志,它的工作。


另一种方法是使用model events,但我不会这样做。

+0

是的,push()是我需要的。我在文档中阅读了它,但他们并不清楚如何使用它。非常感谢。 – aBhijit 2014-09-19 10:45:42

+0

没有问题,只是介意**您不能使用push以相同的方式插入多个模型**。它只适用于现有的型号。 – 2014-09-19 10:47:13

+0

按“存在”,你的意思是“相关”模型的权利? – aBhijit 2014-09-19 10:49:25