【问题标题】:Symfony2 Doctrine - Many-To-Many where querySymfony2 Doctrine - 多对多 where 查询
【发布时间】:2014-01-07 10:16:22
【问题描述】:

在任何事情之前,我尝试了搜索功能,但没有找到关于这个的线程。 这是我的问题。我正在使用具有多对多关系的学说查询构建器。

$qb = $this->getDoctrine()->getRepository('SOMEBUNDLE:INSERTION')->createQueryBuilder('insertion');
      $qb->select('
        insertion.id, 
        insertion.title, 
        insertion.content, 
        insertion.insertionpicture,
        insertion.timestamp,
        insertion.isanon,
        user.firstname as user_firstname, 
        user.lastname as user_lastname,
        user.picture as user_picture,
        supertag.name as supertag_name
        ');
      $qb->from('SOMEBUNDLE:USER', 'user');
      $qb->from('SOMEBUNDLE:SUPERTAG', 'supertag');
      $qb->from('SOMEBUNDLE:TAG', 'tag');
      $qb->andWhere('insertion.user = user.id');
      $qb->andWhere('insertion.supertag = supertag.id');
      $qb->andWhere("insertion.tag = :tag");
      $qb->setParameters('tag', $tags);
      return new JsonResponse($qb->getQuery()->getArrayResult());

插入.php

   /**
     * @var \Doctrine\Common\Collections\Collection
     */
    private $tag;

在“andwhere(insertion.tag = :tag)”中,我的参数是一个数组。我得到了一个无效的路径表达式异常,因为我不知道如何为 Doctrine 集合设置参数。

谢谢

【问题讨论】:

  • $tags参数是什么,是数组吗?
  • 是的,比如:array(2) { [0]=> string(3) "Fun" [1]=> string(4) "Help" }
  • 它们是实体还是数组只包含字符串?

标签: symfony doctrine many-to-many query-builder


【解决方案1】:

尝试替换这个:

$qb->andWhere("insertion.tag = :tag");

通过这个:

$qb->andWhere(
    $qb->expr()->in('insertion.tag', $tags)
);

无论如何,您可以通过链接对查询构建器的调用来减少代码:

$qb = $this->getDoctrine()
    ->getRepository('SOMEBUNDLE:INSERTION')
    ->createQueryBuilder('insertion');

$query = $qb
    # select only some columns from the tables
    ->select('partial insertion.{id, title, content, '.'
        insertionpicture, timestamp, isanon}, '.
        'partial user.{id, firstname, lastname, picture}, '.
        'partial supertag.{id, name} '
    )
    # if the Doctrine association is correct, joins are easy
    ->leftJoin('insertion.user', 'user')
    ->leftJoin('insertion.supertag', 'supertag')
    ->leftJoin('insertion.tag', 'tag')
    ->andWhere(
        $qb->expr()->in('tag.name', $tags)
    );

return new JsonResponse($query->getQuery()->getArrayResult());

【讨论】:

    猜你喜欢
    • 2014-12-20
    • 1970-01-01
    • 2015-04-19
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多