Symfony2/Doctrine QueryBuilder using andwhere()

前端 未结 2 1729
暗喜
暗喜 2021-02-05 17:57

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

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


        
2条回答
  •  囚心锁ツ
    2021-02-05 18:11

    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')
    

提交回复
热议问题