[英]how to get all comments with their post title linked to posts table in laravel?
评论表
+----+---------+------+------+--------+-----------+
| id | post_id | name | text | status | timestamp |
+----+---------+------+------+--------+-----------+
| 1 | 52 | user | test | 1 | timestamp |
+----+---------+------+------+--------+-----------+
帖子
+----+--------+------------------+-----------+
| id | title | description | timestamp |
+----+--------+------------------+-----------+
| 52 | mypost | post description | timestamp |
+----+--------+------------------+-----------+
Commnet.php [laravel 模型]
public function post()
{
return $this->belongsTo('App\Post');
}
Post.php [laravel 模型]
public function comments()
{
return $this->hasMany('App\Comment');
}
我想列出所有带有帖子标题的评论。 如何收集评论集合中包含的帖子标题?
我不想使用 DB::table(); 我希望它通过评论模型收集。 像这样$comments = Comment::all()->post->title;
通常查询看起来像这样( laravel docs ):
$comments = Comment::with('post')->all();
使用这样的数据看起来像这样:
foreach($comments as $comment) {
$comment->name;
$comment->text;
$comment->post->title;
}
如果您希望输出为“平坦”,您还可以执行以下操作( laravel docs ):
$comments = Comment::select('comments.*', 'posts.title')->join('posts', 'post.id', 'comments.post_id')->get()
这样你就可以像这样使用数据:
foreach($comments as $comment) {
$comment->name;
$comment->text;
$comment->title;
}
稍后在您的答案下看到您的评论后,我意识到您可能正在寻找的查询:
$postTitles = Post::select('title')->whereHas('comments')->get()->pluck('title');
这将返回一个帖子标题的集合,只有有评论的帖子标题才会显示。
根据您的最新评论,我可以向您展示如何过滤帖子中的评论( laravel 文档):
$post = Post
::with([
'category',
'comments' => function($query) {
$query->where('status_id', 1);
},
'user'
])
-where('slug', $slug)
->first();
现在您将获得与 slug 相关的第一篇文章,以及所有用户详细信息、所有类别详细信息,但只有status_id
1 的评论
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.