在CakePhp中编写SQL语句(如果为null则分组)

时间:2017-07-12 07:31:06

标签: php cakephp

所以我需要使用 CakePhp ORM 编写 SQL语句,但我在如何使用Cakephp GROUP BY IF NULL(condition)编写时遇到问题。

Here is SQL Statement:
SELECT COUNT(*) FROM
(
    SELECT i.id
    FROM items i
        INNER JOIN orders o ON i.order_id = o.id
    WHERE (
    (i.type = 1 AND i.status = 50) OR ((i.type = 2 OR i.type = 4) AND i.status = 60))
        AND i.date_of_completion IS NOT NULL
        GROUP BY IFNULL(i.vessel_change_identifier, i.id)
) AS temptbl;

这是我的CakePhp查询

$query = TableRegistry::get('Items')
  ->find('all')
  ->innerJoinWith('Orders', function ($q) {
    return $q->where(['Orders.id' => 'Items.order_id']);
  })
  ->Where([
    'Items.type' => 1,
    'Items.status' => 50,
  ])
  ->orWhere([
    'Items.type IN ' => [2, 4],
    'Items.status' => 60,
  ])
  ->andWhere([
    'Items.date_of_completion IS NOT' => NULL
  ]);

$query->select([
  'count' => $query->func()->count('*')
]);

谢谢!

1 个答案:

答案 0 :(得分:1)

尝试使用 - > ifnull()

$query = TableRegistry::get('Items')
      ->find()
      ->innerJoinWith('Orders')
      ->where([
        'Items.type' => 1,
        'Items.status' => 50,
      ])
      ->orWhere([
        'Items.type IN ' => [2, 4],
        'Items.status' => 60,
      ])
      ->andWhere([
        'Items.date_of_completion IS NOT' => NULL
      ]);
    $query
      ->group(
        $query
          ->func()
          ->ifnull([
            'Items.vessel_change_identifier',
            'Items.id'
          ])
      );
    $query->select([
      'count' => $query->func()->count('*')
    ]);

使用它并享受它:D