雄辩的关系错误

Elequent Relationships Error

我为帖子评论创建了帖子 table 和评论 table。 我想得到我的帖子和他们的评论...

在我的 Post 模型中:

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

在我的评论模型中:

public function post()
{
  return $this->belongsTo('App\Post');
}

这是我的控制器:

public function show($ID)
{
    try {
        $post = Post::findOrFail($ID);
        $comments = Post::find($ID)->comments;
        $randomPosts = Post::all()->random(3);
        return view('show', compact('post','comments','randomPosts'));
    } catch (ModelNotFoundException $e) {
        $posts = Post::orderBy('ID', 'DESC')->paginate(5);
        return view('welcome', compact('posts'));            
    }
}

但是我得到这个错误: 未定义 属性:Illuminate\Database\Eloquent\Collection::$ID

我的问题是什么?

您需要将 $ID 变量分配给您要检索的 ID post

例如,假设您想要 ID 为 1 的 post 及其评论。

首先,您可以像这样检索第一篇文章的评论:

$comments = App\Post::find(1)->comments;

foreach ($comments as $comment) {
    echo $comment
}

当然可以检索post代表一条评论

例如第一个评论的post:

$comment = App\Comment::find(1);

echo $comment->post->title;