Symfony2 + Doctrine:多个条件使用数组

时间:2013-10-18 06:42:05

标签: php symfony doctrine-orm

我有一个实体,我正在尝试在其存储库中创建以下函数

function customGet(array $criteria)
{
     //WHAT I'm trying to do:
     //SELECT *
     //FROM mytable
     //LEFT JOIN anothoer table
     //WHERE criteria1 = value1 AND criteria2 = value2 ...etc

     $q = $this
        ->createQueryBuilder('u')
        ->select('u, g')
        ->leftJoin('u.theOtherTable', 'g');
        //Where here
        ->getQuery();
}

我该怎么做where子句?

2 个答案:

答案 0 :(得分:5)

    $q = $this->createQueryBuilder('u')
        ->select('u, g')
        ->leftJoin('u.theOtherTable', 'g');

    foreach ($criteria as $field => $value) {
        $q->andWhere(sprintf('u.%s = :%s', $field, $field))
          ->setParameter($field, $value);
    }

    return $q->getQuery();

答案 1 :(得分:0)

如果所有实体关联都正确完成,您可以这样做

function customGet(array $criteria)
    {
         $value1 = $criteria['0'];   //Your expected value
         $value2 = $criteria['1'];   //Your expected value

     $q = $this
        ->createQueryBuilder('u')
        ->select('u, g')
        ->leftJoin('u.theOtherTable', 'g');
        ->where('criteria1 = :value1 AND criteria2 = :value2')
        ->setParameters(array('value1'=>$value1,'value2'=>$value2))
        ->getQuery();

   return $q->getResult()
}