1

So I need to write SQL statement using CakePhp ORM, but I have problem how to write in 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;

This is my CakePhp Query

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

Thank you!

2
  • And the problem is what exactly? Commented Jul 12, 2017 at 12:18
  • @ndm how to use GROUP BY IFNULL(i.vessel_change_identifier, i.id) from SQL statement in CakePhp $query Commented Jul 12, 2017 at 14:30

1 Answer 1

1

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

Use it and enjoy it :D

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.