条令查询WHERE IN-多对多


Doctrine query WHERE IN - many to many

我正在Symfony2建立一个酒店网站。每家酒店都可以提供多种餐饮选择,如自助式、全包式等。

在我的搜索表单上,用户可以根据所有常用字段进行筛选,如位置、价格、星级和董事会基础。Board基础是一个多选复选框。

当用户选择多个板基选项时,我目前正在以这种方式处理。。。(这是抛出错误)

$repo = $this->getDoctrine()->getRepository("AppBundle:Accommodation");
$data = $form->getData();
$qb = $repo->createQueryBuilder("a")
        ->innerJoin("AppBundle:BoardType", "b")
        ->where("a.destination = :destination")
        ->setParameter("destination", $data['destination'])
        ->andWhere("a.status = 'publish'");
if (count($data['boardBasis']) > 0) {
    $ids = array_map(function($boardBasis) {
        return $boardBasis->getId();
    }, $data['boardBasis']->toArray());
    $qb->andWhere($qb->expr()->in("a.boardBasis", ":ids"))
        ->setParameter("ids", $ids);
}

这是酒店实体的财产声明

/**
 * @ORM'ManyToMany(targetEntity="BoardType")
 * @ORM'JoinTable(name="accommodation_board_type",
 *      joinColumns={@ORM'JoinColumn(name="accommodation_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM'JoinColumn(name="board_type_id", referencedColumnName="id")}
 *      )
 */
private $boardBasis;

我目前得到的错误是:

[语义错误]第0行,第177列,靠近"boardBasis I":错误:无效的PathExpression。应为StateFieldPathExpression或SingleValuedAssociationField。

在提交表格并在板上使用var_dump时,我得到的类型是:

object(Doctrine'Common'Collections'ArrayCollection)[3043]
  private 'elements' => 
    array (size=2)
      0 => 
        object(AppBundle'Entity'BoardType)[1860]
          protected 'shortCode' => string 'AI' (length=2)
          protected 'id' => int 1
          protected 'name' => string 'All-Inclusive' (length=13)
          protected 'description' => null
          protected 'slug' => string 'all-inclusive' (length=13)
          protected 'created' => 
            object(DateTime)[1858]
              ...
          protected 'updated' => 
            object(DateTime)[1863]
              ...
      1 => 
        object(AppBundle'Entity'BoardType)[1869]
          protected 'shortCode' => string 'BB' (length=2)
          protected 'id' => int 2
          protected 'name' => string 'Bed & Breakfast' (length=15)
          protected 'description' => null
          protected 'slug' => string 'bed-breakfast' (length=13)
          protected 'created' => 
            object(DateTime)[1867]
              ...
          protected 'updated' => 
            object(DateTime)[1868]
              ...

我似乎找不到这个查询的正确语法,我过去做过几次(每次都很痛苦),但我就是记不清是怎么做的。我尝试过不映射ID,直接在.中传递ArrayCollection

目前我唯一能想到的就是将其切换为使用createQuery和使用DQL,看看这是否有什么不同。

如果您对此问题有任何帮助,我们将不胜感激,谢谢

在我看来,您的加入还没有完全完成。您缺少一个描述要加入哪个字段的语句:

$qb = $repo->createQueryBuilder("a")
    ->innerJoin("AppBundle:BoardType", "b")
    ->where("a.boardBasis = b.id")
    ...

或者你可以这样加入:

$qb = $repo->createQueryBuilder("a")
    ->innerJoin("a.boardBasis", "b")
    ...

然后你可以添加你的WHERE IN语句,如下所示:

$qb->andWhere('b.id IN (:ids)')
    ->setParameter('ids', $ids);