雄辩ORM -保存记录与2个引用字段


Eloquent ORM - save record with 2 reference fields

如果我创建这样一个注释:

$post->comments()->create(array('body' => 'Comment message'));

我有模型在我的帖子:

public function comments()
{
    return $this->morphMany('Comment', 'shared_comments');
}

填充post和comment之间的多态关系字段

我也有模型在我的评论:

public function author()
{
    return $this->belongsTo('User');
}

我如何在评论表中填写'user_id'字段?

可以直接在数组中指定用户id

$post->comments()->create(array(
    'body' => 'Comment message',
    'user_id' => Auth::user()->id
));

或者,您可以创建评论,然后插入与posts和users表的关系。

$post = Post::find($whatever);
$user = Auth::user()->id;
$comment = Comment::create(array(
    'body' => 'Comment message'
));
$post->comments()->insert($comment);
$user->comments()->insert($comment);

在Laravel 4中,您将在最后两行使用save($comment)而不是insert($comment)