如何使用Doctrine创建内部联接?

时间:2015-08-23 16:39:54

标签: php symfony doctrine-orm dql

我的数据库中有3个表:

  1. 关联
    • ID
    • 标题
  2. 用户
    • ID
    • 名称
  3. association_users
    • ID
    • id_users
    • id_associations
  4. 我想在SQL上执行此查询:

    SELECT a.id, a.title, u.id, u.name
          FROM association AS a
          INNER JOIN association_user AS au
          ON au.association_id = a.id
          INNER JOIN user AS u
          ON u.id = au.user_id
          WHERE au.user_id = ID
    

    目前,我有这个:

            return $this->createQueryBuilder('a')
                        ->join('association.users', 'u')
                        ->addSelect('a')
                        ->join('user.id', 'u.id')
                        ->addSelect('u')
                        ->where("au.user_id = :id")
                        ->setParameter('id', $userid)
                        ->getQuery()
                        ->getResult()
        ;
    

    但它不起作用:

    [Semantical Error] line 0, col 73 near '.users u INNER': Error: Identification Variable association used in join path expression but was not defined before.
    

    我的querybuilder出了什么问题?

    工作代码

    我已将查询更改为:

    'query_builder' => function(EntityRepository $er) {
                        return $er->createQueryBuilder('a')                              
                                ->innerJoin('a.users','u')
                                ->where('u.id = :id')->setParameter('id', $this->getUser()->getId());             
                    },
    

1 个答案:

答案 0 :(得分:0)

如果您的实体映射正确,则querybuilder将自动加入映射中指定的列,您无需再次在此处指定:

$qb->select("a,u")
        ->from('MyBundle\Association','a')
        ->innerJoin('a.users','u')
        ->where('u.id = :id')
        ->setParameter('id',$userid);