将laravel原始SQL查询转换为集合

时间:2017-12-23 23:38:27

标签: mysql laravel-5 highcharts

我正在尝试使用https://erik.cat/projects/Charts/docs/5包在我的laravel项目中显示图表,但我注意到我需要使用模型/集合来为它(数据库)部分工作。以下是文档中的示例

$chart = Charts::database(User::all(), 'bar', 'highcharts');

现在,我没有使用雄辩的ORM进行查询,而是使用原始查询。我不知道如何转换此特定查询,使其返回集合而不是当前返回的数组

$result = DB::select("SELECT DATE(a.created_at) as date, SUM(a.credit) as credit, SUM(a.debit)
        FROM telco_transactions AS a
        WHERE a.telco_id = '1' and DATE(a.created_at) BETWEEN DATE(NOW())-INTERVAL 7 DAY AND DATE(NOW())
        GROUP BY DATE(a.created_at)");

3 个答案:

答案 0 :(得分:0)

您可以使用whereBetween来处理日期,使用DateTime modify来获取第一个日期。

$now = date('Y-m-d H:i:s');
$before = new \DateTime();
$before->modify('-7 days');
$result = TelcoTransaction::where('telco_id', 1)
                          ->whereBetween('created_at', [$before->format('Y-m-d H:i:s', $now])
                          ->groupBy('created_at')
                          ->get();      

请注意,按created_at分组仅适用于日期时间完全相同的内容,包括秒数。

答案 1 :(得分:0)

你好,你可以做这样的事情

$result->toArray();

答案 2 :(得分:0)

如果您确实需要模型,则应使用hydrate()https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html#method_hydrate)对于您提供的示例,代码应如下:

$transactionsData = DB::select("SELECT DATE(a.created_at) as date, SUM(a.credit) as credit, SUM(a.debit)
    FROM telco_transactions AS a
    WHERE a.telco_id = '1' and DATE(a.created_at) BETWEEN DATE(NOW())-INTERVAL 7 DAY AND DATE(NOW())
    GROUP BY DATE(a.created_at)");

return Transactions::hydrate($transactionsData);
  

请注意,如果结果太大而无法在ram中分配,这种方法可能会崩溃

如果不是明确需要模型集合,而只是结果集合,请使用collect()将结果转换为集合:

$transactionsData = DB::select("SELECT DATE(a.created_at) as date, SUM(a.credit) as credit, SUM(a.debit)
    FROM telco_transactions AS a
    WHERE a.telco_id = '1' and DATE(a.created_at) BETWEEN DATE(NOW())-INTERVAL 7 DAY AND DATE(NOW())
    GROUP BY DATE(a.created_at)");

return collect($transactionsData);