我有兩個名為Posts和Comments 的表。
帖子表的樣子。
|id|user_id|content|created_at|updated_at|
|1 | 24 |demotxt|demo_date |demo_date |
|2 | 21 |domotxt|demo_date2|demo_date2|
|3 | 24 |domotxt|demo_date2|demo_date3|
|4 | 28 |dimotxt|demo_date3|demo_date5|
評論表看起來像
|id|user_id|post_id|comment |created_at|updated_at|
|1 | 24 | 3 |comment1|demo_date |demo_date |
|2 | 21 | 3 |xyadbsss|demo_date2|demo_date2|
|3 | 24 | 1 |okayokay|demo_date2|demo_date3|
|4 | 28 | 4 |somehtin|demo_date3|demo_date5|
我想要實作的是獲得每個帖子的第一個最新評論和評論總數。IE
|post_id|latest_comment |total_comments |
| 3 |xyadbsss |2 |
| 1 |okayokay |1 |
| 4 |somehtin |1 |
這是我試過的 sql 查詢
SELECT post_id, count(post_id) total_comments, comment latest_comment
FROM `comments`
LEFT JOIN posts on comments.post_id = posts.id
GROUP BY post_id;
這給了我
|post_id|latest_comment |total_comments |
| 3 |comment1[not latest]|2 |
| 1 |okayokay |1 |
| 4 |somehtin |1 |
uj5u.com熱心網友回復:
你可以嘗試這樣的事情,不確定是否是最好的解決方案。
SELECT
c1.post_id,
count(c1.`post_id`) total_comments,
(
SELECT
c2.comment
FROM
comments as c2
WHERE
c2.post_id = c1.`post_id`
ORDER BY
c2.id DESC LIMIT 1
) as latest_comment
FROM
`comments` as c1
GROUP BY
c1.`post_id`;
我寧愿回圈第一個資料并根據帖子 ID 進行另一個查詢以獲取最新評論。
uj5u.com熱心網友回復:
要獲取資料庫中的最新記錄,您可以使用它
Model::latest()->first();
因此,在您的情況下,要獲取最新評論:
Comment::latest()->first()['comment'];
您也可以根據您的 Laravel 版本使用此方法(如果您使用 5.7 或更高版本):
DB::table('comments')->latest('comment')->first();
現在要計算帖子的所有評論,您可以使用帖子 ID 查找所有評論并使用 count 屬性
$count = Comment::where('post_id',$the_id_of_the_post)->count();
uj5u.com熱心網友回復:
實作此目的的一種方法是使用latestOfMany方法。將以下內容添加到您的Post模型中:
public function latestComment()
{
return $this->hasOne(Comment::class)->latestOfMany();
}
然后你可以預先加載結果:
$posts = Post::with('latestComment')->withCount('comments as total_comments')->get();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365700.html
下一篇:SQL選擇不同列上的組
