createQueryBuilder / Join Column - Symfony

时间:2016-09-06 14:42:12

标签: php mysql left-join symfony

我无法实现此SQL请求:

SELECT *
FROM project
LEFT JOIN user 
ON project.idAuthor=user.id 
WHERE project.isVisible = 1 AND
user.role = 'agency'

到一个简单的Symfony查询生成器:

 $query = $this->createQueryBuilder('p')
            ->leftJoin('WebAwardsBundle:User', 'u')
            ->where('p.isVisible = 1')
            ->andwhere("u.role = 'agency'")
            ->orderBy('p.id', 'DESC')
            ->getQuery();

此查询的响应为我提供了所有项目,包括角色时的项目!==代理......

我不知道我可以将ON project.idAuthor=user.id

放在哪里

映射:

项目:

    /**
 * Project
 *
 * @ORM\Table(name="project")
 *@ORM\Entity(repositoryClass="WebAwardsBundle\Repostory\ProjectRepository")
 */
class Project
{
    ...
/**
 * @var int
 *
 * @ORM\ManyToOne(targetEntity="User", inversedBy="projects")
 * @ORM\JoinColumn(name="idAuthor", referencedColumnName="id")
 */
private $idAuthor;

...

用户:

/**
 * User
 *
 * @ORM\Table(name="user")
 * @ORM\Entity(repositoryClass="WebAwardsBundle\Repository\UserRepository")
 */
class User implements UserInterface, \Serializable{

...

 /**
     * @ORM\OneToMany(targetEntity="Project", mappedBy="idAuthor")
     */
    private $projects;
...

1 个答案:

答案 0 :(得分:0)

实现此SQL请求的正确答案:

SELECT *
FROM project
LEFT JOIN user 
ON project.idAuthor=user.id 
WHERE project.isVisible = 1 AND
user.role = 'agency'

是加入实体的正确列(在这种情况下是project.idAuthor给用户):

$query = $this->createQueryBuilder('p')
        ->join('p.idAuthor', 'u')
        ->where('p.isVisible = 1')
        ->andWhere("u.role = 'agency'")
        ->orderBy('p.id', 'DESC')
        ->getQuery();