【发布时间】:2018-05-23 05:11:29
【问题描述】:
我有模型正常运行时间。如何使用模型查询进行此查询?
SELECT server_id, COUNT(*) status FROM uptime WHERE online = 0 GROUP BY server_id
我试试:
Uptime::where('online', 0)->get();
但这是不正确的。我需要 COUNT(*) 并按选择分组。
【问题讨论】:
我有模型正常运行时间。如何使用模型查询进行此查询?
SELECT server_id, COUNT(*) status FROM uptime WHERE online = 0 GROUP BY server_id
我试试:
Uptime::where('online', 0)->get();
但这是不正确的。我需要 COUNT(*) 并按选择分组。
【问题讨论】:
Uptime::whereOnline(0)
->groupBy('server_id')
->select('server_id', DB::raw('count(*) as status'))
->get();
whereOnline 是where('online', 0) 的快捷方式
【讨论】:
Uptime::select('server_id', DB::raw('COUNT(*) as status'))
->where('online',0)
->groupBy('server_id')
->get();
【讨论】:
根据 laravel 文档Raw Expressions
此代码是您查询COUNT(*) 和GROUP BY 的适当方式
DB::table('uptime')->select(DB::raw('COUNT(*) as status'))
->where('online',0)
->groupBy('server_id')
->get();
原始语句将作为字符串注入到查询中,因此您应该非常小心,不要造成 SQL 注入漏洞。
【讨论】: