使用doctrine中的SQL IN语句筛选查询

时间:2012-10-19 06:44:05

标签: symfony doctrine-orm dql

一个分支机构可能有许多客户,客户可能与许多分支机构有关。所以这是一个多对多的关系。

科:

<many-to-many target-entity="Customer" inversed-by="branches" field="customers"/>

客户:

<many-to-many field="branches" target-entity="Branch" mapped-by="customers"/>

现在我想执行以下查询:选择客户分支与给定分支对象匹配的所有客户。

这就是我的尝试:

  $branch = $em->getRepository('MyBundle:Branch')
               ->findOneById($bid);

  $qb->select(array('c'))
     ->from('MyBundle:Customer', 'c')
     ->where($qb->expr()->in('c.branches', $branch))
     ->andWhere('c.delted = 0')
     ->getQuery();

所以我的想法是使用IN语句。但这不起作用。

错误:

  

致命错误:类DateTime的对象无法转换为字符串   第48行的..Query \ Expr \ Func.php

任何想法如何以正确的方式做到这一点?

1 个答案:

答案 0 :(得分:2)

在您的查询中尝试添加联接:

$qb->select(array('c', 'b'))
    ->from('MyBundle:Customer', 'c')
    ->join('c.branches', 'b')
    ->where('b IN (:branch)')
    ->andWhere('c.deleted = 0')
    ->setParameter('branch', array($branch))
    ->getQuery();