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

trr*_*rrm 1 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();
}
Run Code Online (Sandbox Code Playgroud)

我该怎么做where子句?

Lee*_*ulb 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();
Run Code Online (Sandbox Code Playgroud)

  • 如果可能的话,您应该尝试在Join上"过滤",但此外,我认为这是编写专用查询的好习惯. (2认同)