Laravel Eloquent有很多关系

时间:2015-05-23 12:36:35

标签: php laravel eloquent

您好我是Laravel的新手,目前正在使用Laravel 4.2。我正在尝试创建一个应用程序,其中我有用户,帖子和评论表,并具有以下模型

用户模型

function posts() {

    return $this->hasMany('Post');
}


function comments(){

    return $this->hasMany('Comment');
}

发布模型

function users() {

    return $this->belongsTo('User');
}

function comments() {

    return $this->hasMany('Comment');
}

评论模型

function posts(){

    return $this->belongsTo('Post');
}

function users(){

    return $this->belongsTo('User');
}

我想要实现的目标:

用户对帖子的发布和评论

eg:: User1 -> Post one -> comment for post one

到目前为止我做了什么:::

$user = User::find(1);
$post = $user->posts()->get();

我能够发帖,但我如何得到特定帖子的评论?

更新

感谢@Bogdan的帮助,我能够为用户发帖和评论。但像往常一样有另一个问题。

我得到了什么:

 foreach($user->post AS $post) {

 foreach ($post->comment AS $comment ) {

 $comment->commentcontent; $user->uername;
}
}//first foreach

这就是我得到的

comment one by user1.
comment two by user1.

但实际上,注释1是由user1创建的,注释2是由user2创建的。

提前感谢您的帮助。如果需要,可以发布完整代码。

2 个答案:

答案 0 :(得分:3)

当您检索用户时在$user->posts()->get()的帖子中,您获得了Collection Models,您可以使用find获取所需的特定帖子。然后,您可以像检索用户一样检索帖子的评论'帖子:

$user = User::find(1);
$post = $user->posts()->find($postId);
$comments = $post->comments;

如果您想迭代整个帖子集合,您可以单独访问每个帖子的评论,而无需过滤特定帖子:

foreach ($user->posts as $post)
{
    $comments = $post->comments;
}

此外,为了将来参考,将关系作为属性访问将返回Collection,而作为方法访问关系将返回Query Builder实例。因此$user->posts$user->posts()->get()相同。

答案 1 :(得分:1)

您希望获得发表评论的用户,因此请从评论对象中获取该用户。

试试这个

$user = User::find(1);
$posts = $user->posts;

foreach ($posts as $post) {
    foreach ($post->comments as $comment) {
        echo $comment->commentcontent;
        echo $comment->users;
    }
}