Symfony多对多关联查询报错:Expected Literal, got 'entity' 求解
修正Symfony多对多关联的QueryBuilder语法错误
原代码的问题在于错误使用IN语句处理多对多关联,DQL不支持location.id IN (entity.locations)这种写法,因为entity.locations是关联集合,不能直接作为IN的取值列表。
正确的写法是直接通过实体的关联字段建立Join关系,无需手动用IN匹配ID:
$queryBuilder ->leftJoin('entity.locations', 'location') ->andWhere('location.institute = :institute') ->setParameter('institute', $user->getInstitute());
关键说明:
- 实体与Location是多对多关联,直接引用
entity.locations即可关联到对应的Location实体,这是Doctrine处理关联查询的标准方式。 - 如果只需要保留关联了符合条件Location的实体,可以将
leftJoin改为innerJoin,过滤掉没有匹配Location的结果。
内容的提问来源于stack exchange,提问作者someStudentCS
相关产品推荐
相关产品推荐

