简体   繁体   中英

How to fetch comments where $comments->post_id = $post->id with Laravel?

Okay,

So I can't figure this one out. Eloquent model is new to me.

I'm trying to fetch comments for specific posts.

This is my post model :

<?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');
    }
}

Comment model:

<?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');
    }
}

Routes:

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 might be unnecessary?)

View:

@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>

I tried to loop through the comments using:

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

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

@endwhile

I got an error message "Undefined property: Illuminate\\Database\\Eloquent\\Collection::$body" even though the comments table have a column named "body".

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

Is what you want. You can use eager loading in the query to speed this up as well:

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

You code with create multiple queries because of $post->user->first_name . For example, if you have 70 posts, your code will create 72 query which is awful.

It's much better to use eager loading to load posts with comments and users. This code will create just 3 queries:

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

And then itarate over collection:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM