【问题标题】:Laravel convert query mysql to model queryLaravel 将查询 mysql 转换为模型查询
【发布时间】: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(*) 并按选择分组。

【问题讨论】:

标签: php laravel


【解决方案1】:
Uptime::whereOnline(0)
    ->groupBy('server_id')
    ->select('server_id', DB::raw('count(*) as status'))
    ->get();

whereOnlinewhere('online', 0) 的快捷方式

【讨论】:

    【解决方案2】:
    Uptime::select('server_id', DB::raw('COUNT(*) as status'))
            ->where('online',0)
            ->groupBy('server_id')
            ->get();
    

    【讨论】:

      【解决方案3】:

      根据 laravel 文档Raw Expressions

      此代码是您查询COUNT(*)GROUP BY 的适当方式

      DB::table('uptime')->select(DB::raw('COUNT(*) as status'))
          ->where('online',0)
          ->groupBy('server_id')
          ->get();
      

      原始语句将作为字符串注入到查询中,因此您应该非常小心,不要造成 SQL 注入漏洞。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多