dongnan1989 2016-12-14 11:19
浏览 331
已采纳

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

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".

展开全部

  • 写回答

2条回答 默认 最新

  • douxian6260 2016-12-14 11:25
    关注
    @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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部