Laravel 5: 获取评论

Laravel 5: Fetch comments

我正在构建一个博客评论系统。

我想在 show.blade.php 中显示用户的评论。

在我的 ResultsController 中我执行了

dd($post->comments);

但是我无法从我的数据库中检索任何评论。

我在 post 中植入了四个评论。 用户可以回复每条评论。

迁移table

Schema::create('comments', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('user_id');
        $table->integer('post_id');
        $table->text('body');
        $table->integer('comment_id')->nullable();
        $table->timestamps();
    });

Comment.php

public function posts()
{
    return $this->belongsTo(Post::class);
}

public function user()
{
    return $this->belongsTo(User::class);
}

public function replies()
{
    return $this->hasMany(Comment::class, 'comment_id')->whereNotNull('comment_id');
}

Post.php

 public function comments()
{
    return $this->hasMany(Comment::class)->whereNull('comment_id');
}

User.php

public function comments()
{
    return $this->hasMany(Comment::class);
}

Mysql

ResultsController.php

 public function show($id,Post $post)
{
    $particular_post= Post::find($id);
    $recommended_posts = Post::latest()
                            ->whereDate('date','>',date('Y-m-d'))
                            ->where('category_id','=',$particular_post->category_id)
                            ->where('id','!=',$particular_post->id)
                            ->limit(7)
                            ->get();

    $posts['particular_post'] = $particular_post;
    $posts['recommended_posts'] = $recommended_posts;

    dd($post->comments);

    return view('posts.show',compact('posts'));
}

http://127.0.0.1:8000/results/52 这是应该获取评论的 URL。

方法注入只有在路由映射中的变量和函数的参数同名时才有效,你也只需要接受 post 本身作为参数,你不需要两者post 及其 ID。

将您的 show 函数更改为:

public function show(Post $post)
{
    $recommended_posts = Post::latest()
                            ->whereDate('date','>',date('Y-m-d'))
                            ->where('category_id','=',$post->category_id)
                            ->where('id','!=',$post->id)
                            ->limit(7)
                            ->get();

    $posts['particular_post'] = $post;
    $posts['recommended_posts'] = $recommended_posts;

    dd($post->comments);

    return view('posts.show',compact('posts'));
}

然后确保路由映射中的变量与show的参数同名,即:

Route::get('results/{post}', 'ResultsController@show');