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条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)