2017-07-12 64 views
1

所以我需要編寫使用CakePHP的ORMSQL語句,但我有問題,如何在CakePHP的GROUP BY IF NULL(condition)寫。寫SQL語句(如果由空組)

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('*') 
]); 

謝謝!

+0

而問題是究竟是什麼? – ndm

+0

@ndm如何從CakePhp的SQL語句中使用GROUP BY IFNULL(i.vessel_change_identifier,i.id)$ query – JohnWayne

回答

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

+0

@FreeMoonSpider thx – JohnWayne