如何在cakephp 2中的查询中创建动态列

时间:2019-02-20 05:43:43

标签: cakephp

我遇到了麻烦。我为此卡了几个小时。我想发生的是将日期范围显示为查询中的另一列。所以我有这个查询

  SELECT id, created, 
    COUNT(IF(DATE(created) = "2019-02-01",1, null)) AS "2019-02-01",
    COUNT(IF(DATE(created) = "2019-02-01",2, null)) AS "2019-02-02",
    COUNT(IF(DATE(created) = "2019-02-03",1, null)) AS "2019-02-03",
    COUNT(IF(DATE(created) = "2019-02-04",1, null)) AS "2019-02-04",
    COUNT(IF(DATE(created) = "2019-02-05",1, null)) AS "2019-02-05"
    FROM logs WHERE DATE(created) = "2019-02-01" AND message= 'Login' AND username = 'aaa@example.com';

我在上面的查询中得到了这个结果 this is the reult when execute the query

所以要以cakephp的方式将其转换为我所做的

     $start = strtotime($start_date);
        $end = strtotime($end_date);

        $dates = [];
        for ($currentDate = $start; $currentDate <= $end;  
            $currentDate += (86400)) { 

            $Store = date('Y-m-d', $currentDate); 
            $dates[] = $Store; 
        } 

           foreach ($dates AS $d) {
               $logs = $this->Log->find("all", [

                'fields' => ['Log.id',
                    'Log.created',
                    'COUNT(IF(DATE(Log.created) = "'.$d.'",1, null)) AS "'.$d.'"'
                ],
                'conditions' => $conditions,

            ]);

但是这段代码给了我不同的输出。它只显示一个日期

Array
(
    [0] => Array
        (
            [Log] => Array
                (
                    [id] => 46260
                    [created] => 2019-02-05 11:10:12
                )

            [0] => Array
                (
                    [2019-02-05] => 1
                )

        )
)

我期望的输出是这样的

 Array
(
    [0] => Array
        (
            [Log] => Array
                (
                    [id] => 46260
                    [created] => 2019-02-05 11:10:12
                )

            [Date] => Array
                (
                    [2019-02-01] => 4,
                    [2019-02-02] => 0,
                    [2019-02-03] => 0,
                    [2019-02-04] => 0,
                    [2019-02-05] => 0,

                )

        )
)

我想知道我的工作出了什么问题以及如何使其正确。预先感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您正在运行一个新查询,并每次都通过foreach循环覆盖上一个查询的结果。您想要的是在其中建立字段列表,然后只运行一个查询。

$fields = ['Log.id', 'Log.created'];
foreach ($dates AS $d) {
    $fields[] = 'COUNT(IF(DATE(Log.created) = "'.$d.'",1, null)) AS "'.$d.'"';
}
$logs = $this->Log->find("all", compact('fields', 'conditions'));

实际上,如果您没有在其他任何地方使用该$dates变量,则可以合并两个循环。

$fields = ['Log.id', 'Log.created'];
for ($currentDate = $start; $currentDate <= $end; $currentDate += (86400)) {
    $d = date('Y-m-d', $currentDate);
    $fields[] = 'COUNT(IF(DATE(Log.created) = "'.$d.'",1, null)) AS "'.$d.'"';
} 
$logs = $this->Log->find("all", compact('fields', 'conditions'));