12

I am using following method in a repository class to look for certain tags in my database:

public function getItemsByTag($tag, $limit = null)
{
    $tag = '%'.$tag.'%';

    $qb = $this->createQueryBuilder('c');

    $qb->select('c')
       ->where($qb->expr()->like('c.tags', '?1'))
       ->setParameter(1, $tag)
       ->addOrderBy('c.clicks', 'DESC');

    if (false === is_null($limit))
        $qb->setMaxResults($limit);

    return $qb->getQuery()->getResult();
}

This works just nice.. But: How can I add 2 additional variables (where: reviewed = 1, enabled = 1)? I tried andwhere() but I couldn't figure it out.

I also found out that something like this:

public function getItems($limit = null)
{
        $qb = $this->createQueryBuilder('b')
               ->select('b')
               ->add('where', 'b.reviewed = 1')
               ->add('where', 'b.enabled = 1')
               ->addOrderBy('b.name', 'ASC');

        // ...
}

won't work either...

Any hints?

Mike
  • 2,686
  • 7
  • 44
  • 61

2 Answers2

31

I would write it like this:

$qb = $this
    ->createQueryBuilder('c')
    ->where('c.tags LIKE :tag')
    ->andWhere('c.reviewed = 1')
    ->andWhere('c.enabled = 1')
    ->setParameter('tag', "%{$tag}%")
    ->orderBy('c.clicks', 'DESC')
    ->addOrderBy('b.name', 'ASC');

if ($limit) {
    $qb->setMaxResults($limit);
}

return $qb->getQuery()->getResult();

You could also unite those where conditions:

->where('c.tags LIKE :tag AND c.reviewed = 1 AND c.enabled = 1')
Elnur Abdurrakhimov
  • 44,533
  • 10
  • 148
  • 133
  • 1
    I believe addOrderBy is used is you are concatenating logic to the orderBy. For instance if you wanted 2 orderBy parameters, the first would be 'orderBy', followed by 'addOrderBy'. Works the same as the where clause. The first is ->where, then all following are written '->addWhere'. – Carey Estes Jan 23 '14 at 22:26
  • 1
    Thanks, saved me some time. – Pierrick Martellière Jul 31 '18 at 14:36
6

From the manual, the suggested way is like below:

$qb->select(array('c'))
   ->where($qb->expr()->orx(
       $qb->expr()->eq('c.reviewed', 1),
       $qb->expr()->eq('c.enabled', 1),
       $qb->expr()->like('c.tags', '?1')
   ))
   ->orderBy('c.clicks', 'DESC'));
Niklas
  • 13,005
  • 23
  • 79
  • 119
xdazz
  • 158,678
  • 38
  • 247
  • 274