Doctrine Mysql:查询构建器

时间:2016-08-31 09:49:15

标签: php mysql symfony doctrine-orm

我有实体:TagUserServiceTagUserService有多对多的关系。

 class Service{
      /**
       * @ORM\ManyToMany(targetEntity="Tag", mappedBy="serviceList")
       */
       private $tagList;
 }

 class User{
       /**
        * @ORM\ManyToMany(targetEntity="Tag", mappedBy="userList")
        */
       private $tagList;
 }

 class Tag{
       /**
        * @ORM\ManyToMany(targetEntity="User", inversedBy="tagList")
        * @ORM\JoinTable(name="tags_users")
        */
       private $userList;

       /**
        * @ORM\ManyToMany(targetEntity="Service", inversedBy="tagList")
        * @ORM\JoinTable(name="tags_services")
        */
       private $serviceList;
 }

使用查询构建器,如何返回至少具有给定User的1个公共标记的所有服务,即与用户相关的服务

这是我写的一个查询,但它不起作用

  $query = $em->getRepository('AppBundle:Service')
        ->createQueryBuilder('service')
        ->join('service.tagList', 'serviceTag')
        ->join('AppBundle:BasicUser', 'user')
        ->join('user.tagList', 'userTag')
        ->where('user.id = :id')
        ->andWhere('serviceTag.id = userTag.id')
        ->setParameter('id', $user->getId())
    ;

错误:

 [Syntax Error] line 0, col 104: Error: Expected Literal, got "JOIN" (500 Internal Server Error)

1 个答案:

答案 0 :(得分:3)

您的查询错误。我认为最简单的解决方案是:

 $query = $em->getRepository('AppBundle:Service')
             ->createQueryBuilder('service')
             ->innerJoin('service.tagList', 'tag')
             ->andWhere(':user MEMBER OF tag.userList')
             ->setParameter('user',$user)
             ;