首页 文章

Laravel Eloquent有很多关系

提问于
浏览
1

嗨,我是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();

我能够发帖但我怎么得到具体帖子的评论?

Update

感谢@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.

但实际上,注释一是由user1创建的,注释二是由user2创建的 .

提前谢谢你的帮助 . 如果需要,可以发布完整代码 .

2 回答

  • 3

    当您使用 $user->posts()->get() 检索用户的帖子时,您会得到 Collection Models ,您可以使用 find 获取所需的特定帖子 . 然后你可以检索帖子's comment the same way you retrieved the users'帖子:

    $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

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

    试试这个

    $user = User::find(1);
    $posts = $user->posts;
    
    foreach ($posts as $post) {
        foreach ($post->comments as $comment) {
            echo $comment->commentcontent;
            echo $comment->users;
        }
    }
    

相关问题