Search code examples
cakephpconditional-statementsexpression

How to use an isNull expression in an OR condition


Cakephp Version: 4.3.5

I'm trying to construct an Or condition that uses an isNull expression in a custom finder.

In text I am trying to do this:

public function findMyTasks(Query $query, array $options): object
{
   $query
      ->where([
         'Tasks.status' => $options['status'],
         'Tasks.user_id' => $options['user_id'],
         'OR' => [
             ['Tasks.contact_id' => null], // HERE IS THE CONDITION
             ['Contacts.status' => 1]
         ],
      ]);

    return $query;

 }

If I wanted to use isNull in a condition without OR I would use the following:

->where(function (QueryExpression $exp, Query $q) {
   return $exp->isNull('Tasks.contact_id');
})

I have tried various combinations by referencing the advanced condition page here but I cannot combine the expression with the condition without a syntax error.

Question:

How can I construct this finder that uses isNull with an OR condition.

Thanks, Zenzs.


Solution

  • As documented:

    'OR' => [
        ['Tasks.contact_id IS' => null],
        ['Contacts.status' => 1]
    ],
    

    Just a bit further down on that page: https://book.cakephp.org/4/en/orm/query-builder.html#automatic-is-null-creation