問題描述
在 Laravel 的表中計算 user_id (Count user_id in a table in Laravel)
我想使用下面的查詢。
SELECT `name`, COUNT(`user_id`) AS total, SUM(`status` = 'Done') as done
FROM posts GROUP BY `name`, `user_id`, `status`
但是當我實現這個...
Post::selectRaw('count(user_id) as total')
‑>selectRaw('SUM(status = "Done") as done')
‑>groupBy('name')
‑>get();
我的數據表沒有顯示任何數據。我的查詢有問題嗎?
參考解法
方法 1:
This should work:
$posts = DB::table('posts')‑>select(DB::raw('count(user_id) as total'))‑>selectRaw('SUM(status = "Done") as done')‑>groupBy('name')‑>get();
Since you didnt provide any info about the models, migrations or logic, im guessing that you have everything else set up correctly.
Also the links that Mohamed Bdr added are great examples and I recommend checking them out.
(by Vysco Zyza、dz0nika)