【发布时间】:2020-01-31 14:51:11
【问题描述】:
我正在构建一个博客评论系统。
我想在 show.blade.php 中显示用户的 cmets。
在我的ResultsController中我执行了
dd($post->cmets);
但我无法从我的数据库中检索任何 cmets。
我在一个帖子中播种了四个 cmets。 并且用户可以回复每一条评论。
迁移表
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');
}
用户.php
public function comments()
{
return $this->hasMany(Comment::class);
}
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 这是应该获取 cmets 的 URL。
【问题讨论】:
-
->whereNull('comment_id')不应该是->whereNotNull('comment_id')吗? -
为什么
whereNull? -
因为我只想获取第一个 cmets。每条评论都有comment_id,是对一条评论的回复。
-
@kerbholz 我试过了,但没用。
-
return $this->hasMany(Comment::class)->limit(1)获取单个评论
标签: php sql laravel get comments