[英]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.