Symfony2 Querybuilder选择

时间:2016-09-27 23:02:36

标签: mysql symfony doctrine-orm query-builder

我有3个实体,用户,专家,引文。

Specialist.php

/**
 * 
 * @ORM\OneToMany(targetEntity="Citation", mappedBy="specialist")
 */
protected $citation;

user.php的

/**
 * @ORM\OneToMany(targetEntity="Citation", mappedBy="user", cascade={"remove"})
 */
protected $citation;

Citation.php

/**
 * @ORM\ManyToOne(targetEntity="Specialist", inversedBy="citation")
 * @ORM\JoinColumn(name="specialist_id", referencedColumnName="id")
 */
protected $specialist;

/**
 * @ORM\ManyToOne(targetEntity="User", inversedBy="citation")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 */
protected $user;

在我的数据库中,我有这些注册表:

专家表:

+----------+----------------+
| id       | name           |
+----------+----------------+
| 1        | Specialist One |
| 2        | Specialist Two |
+----------+----------------+

用户表:

+----------+----------+
| id       | name     |
+----------+----------+
| 1        | User One |
+----------+----------+

引文表:

+----------+--------------+---------------+---------+
| id       | name         | specialist_id | user_id |
+----------+--------------+---------------+---------+
| 1        | Citation One | 1             | 1       |
+----------+--------------+---------------+---------+

我需要让所有没有引用用户1的专家。

如果我试试这个, SpecialistRepository.php

public function findSpecialistCitationWithUser($user) {

    $query = $this->createQueryBuilder('s')
        ->leftJoin('s.citation', 'c')
        ->where('c.user = :user')->setParameter('user', $user)
        ->getQuery()
    ;

    return $query->getResult();
}

See it working at SQL Fiddle. 返回用户引用的Specilist。

我正在尝试使用此Querybuilder SpecialistRepository.php

public function findSpecialistNoCitationWithUser($user) {

    $query = $this->createQueryBuilder('s')
        ->leftJoin('s.citation', 'c')
        ->where('c.user <> :user')->setParameter('user', $user)
        ->getQuery()
    ;

    return $query->getResult();
}

See it working at SQL Fiddle. 返回无结果,空

1 个答案:

答案 0 :(得分:0)

使用@geoB帮助,这就是答案:

public function findSpecialistNoCitationWithUser($user) {

    $em = $this->getEntityManager();
    $rsm = new ResultSetMapping();
    $rsm->addEntityResult('AppBundle:Specialist', 's');
    $rsm->addFieldResult('s', 'id', 'id');
    $rsm->addFieldResult('s', 'name', 'name');

    $query = $em->createNativeQuery('SELECT *
        FROM specialist c0_ 
        WHERE c0_.id NOT IN (
          SELECT c1_.specialist_id 
          FROM citation c1_
          WHERE c1_.user_id = 1
        ');

    $specialist = $query->execute();

    return $specialist;

}