如何使用Laravel获取$ comments-> post_id = $ post-> id的评论?

时间:2016-12-14 19:19:20

标签: php laravel blade

好,

所以我无法解决这个问题。 雄辩的模型对我来说是新的。

我试图获取特定帖子的评论。

这是我的帖子模型

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User'); 
    }

    public function likes()
    {
        return $this->hasMany('App\Like');
    }

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

评论模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
    public function post()
    {
        return $this->belongsTo('App\Post');
    }
}

路线:

public function getDashboard(){
        $posts = Post::orderBy('created_at', 'desc')->get(); // MySQL ORDER BY
        $comments = Comment::orderBy('created_at', 'desc')->get();

        return view('dashboard', ['posts' => $posts], ['comments' => $comments]);
    }

($ comments可能没必要?)

查看:

@foreach($posts as $post)

        <article class="post" data-postid=" {{ $post->id }} ">
            <p>{{ $post->body }}</p>
            <div class="info">
                Posted by {{$post->user->first_name}}  on {{ $post->created_at }}
            </div>
</article>

我尝试使用以下方式遍历评论:

@while($comments->post_id = $post->id)

   <p>{{$comments->body}}</p>

@endwhile

我收到错误消息&#34; Undefined property:Illuminate \ Database \ Eloquent \ Collection :: $ body&#34;即使注释表有一个名为&#34; body&#34;。

的列

2 个答案:

答案 0 :(得分:2)

@foreach($post->comments as $comment)

是你想要的。您可以在查询中使用预先加载来加快速度:

Post::with('comments')->orderBy('created_at', 'desc')->get()

答案 1 :(得分:2)

您使用$post->user->first_name创建多个查询进行编码。例如,如果您有70个帖子,那么您的代码将创建72个查询,这很糟糕。

使用eager loading加载包含评论和用户的帖子会更好。此代码将只创建3个查询:

Post::orderBy('created_at', 'desc')
    ->with(['user', 'comments' => function ($q) {
        $q->orderBy('created_at', 'desc');
    }])->get();

然后把它收藏起来:

@foreach ($posts as $post) {
    <article class="post" data-postid=" {{ $post->id }} ">
    ....
    @foreach ($post->comments as $comment) {
        $comment->content;
    }
}