dongnan1989 2016-12-14 19: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 19: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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题