Combining and and or operators in Phalcon\Mvc\Model\Criteria

1.6k Views Asked by At

I'm just writing my first phalcon application and have a question for filtering a query using Phalcon\Mvc\Model\Criteria.

Finally I want a query like this

SELECT * 
FROM table 
WHERE 
  status = 'A' AND
  (
    title LIKE 'combining%' OR
    title LIKE 'phalcon%' OR
    (
      title LIKE 'criteria%' AND
      title LIKE '%phalcon'
    )
  )

For me it seems there is no way for parenthesis in phalcons model criteria. The only way to achieve this is by writing phql.

Instead of writing a complete phql I maybe can write something like this, but that is getting the same complexity

<?php

$query = Table::query();
$query->where('status = :status:', array('status' => 'A'));
$query->andWhere('(
  title LIKE :title1: OR 
  title LIKE :title2: OR (
    title LIKE :title3: AND 
    title LIKE :title4:
  )
)', array(
  'title1' => 'combining%',
  'title2' => 'phalcon%', 
  'title3' => 'criteria%',
  'title4' => '%phalcon'
));
1

There are 1 best solutions below

1
On

It looks like Criteria's "where", "andWhere" and "orWhere" methods will add the outer parenthesis for you, then you can manually write the inner parenthesis.

$query = Model::query()
        ->where('status = "A"')
        ->andWhere('title LIKE "combining%" OR
            title LIKE "phalcon%" OR
            (
                title LIKE "criteria%" AND
                title LIKE "%phalcon"
            )
        ');
$models = $query->execute();

You can test that the where clause is correct.

var_dump($query->getWhere());