我在试着让助理去工作。
用户模型上的关系:
public function group()
{
return $this->belongsTo('User');
}所以我这么做了:
$user = new User();
//save user fields
....
$user->save();
$group = Group::find(1);
$user->group()->associate($group);插入了一个新用户,但是在user表的group_id的FK中,我得到了null。
发布于 2016-11-29 01:41:10
关联需要在保存之前。
$user = new User();
//save user fields
....
$group = Group::find(1);
$user->group()->associate($group);
$user->save();发布于 2016-11-29 01:41:25
好吧,假设您想要将评论与博客帖子相关联,因为评论只能是针对我们将使用associate的特定帖子。在我们的Post模型中,我们将拥有以下内容:
public function comments(){
return $this->hasMany('App\Comment');
}在我们的评论模型中,我们有:
public function post(){
return $this->belongsTo('App\Post');
}在我们的CommentsController中,我们将拥有以下内容:
$comment = new Comment;
$post=Post::find($post_id);
$comment->post()->associate($post);
$comment->save();请注意,只有在将其与帖子关联之后才能保存它。
发布于 2016-11-29 01:42:07
关联后需要保存用户
$user->save();完整代码
$user = User::create([
'field1' => $request->field1,
....
]);
$group = Group::find(1);
$user->group()->associate($group);
$user->save();https://stackoverflow.com/questions/40850070
复制相似问题