Doctrine 2复合键和DQL连接

时间:2013-03-02 21:44:27

标签: php join doctrine-orm dql composite-key

我正在尝试过滤掉父级由复合主键组成的子级,父级称为主语,子级是课程:

主题:

class Subject
{
   /**
     * @var integer
     *
     * @Column(type="integer")
     * @Id
     * @GeneratedValue(strategy="NONE")
     */
    protected $id;

    /**
     * @var integer
     *
     * @Column(type="integer")
     * @Id
     */
    protected $customer_id;

    /**
     * @var ArrayCollection
     *
     * @OneToMany(targetEntity="Course", mappedBy="subject")
     */
    private $courses;

    ...
}

课程:

class Course
{
    ...

    /**
     * @var Subject
     *
     * @ManyToOne(targetEntity="Subject", inversedBy="courses")
     * @JoinColumns({
     *   @JoinColumn(name="subject_id", referencedColumnName="id"),
     *   @JoinColumn(name="subject_customer_id", referencedColumnName="customer_id")
     * })
     */
    private $subject;
}

我有“subject_id”和“subject_customer_id”,我的问题是,当我写这篇文章时,我无法过滤掉没有加入主题的课程:

$this->em->createQuery("SELECT c FROM Course c WHERE c.subject = :subject")
    ->setParameters( array('subject' => array( 'subject_id' => $subject_id, 'subject_customer_id' => $subject_customer_id ) ) )
    ->getResult();

我收到以下错误:

  

Doctrine \ ORM \ Query \ QueryException [0]:单值关联   具有复合主键的实体的路径表达式不是   支持的。明确命名复合主键的组件   在查询中。

我能够实现这一目标的唯一原因是内部联合主题,例如:

$this->em->createQuery("SELECT c FROM Course c INNER JOIN c.subject s WITH s.id = :subject AND s.customer_id = :customer")
    ->setParameters( array( 'subject' => $subject_id, 'customer' => $customer_id ) )
    ->getResult();

有没有办法在不加入主题的情况下根据主题主键检索课程?

1 个答案:

答案 0 :(得分:2)

截至当前日期,此逻辑为not yet supported by DQL(另请参阅https://github.com/doctrine/doctrine2/blob/2.3.2/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php#L1641-L1643)。

您必须加入以下内容:

SELECT
    c
FROM
    Course c
INNER JOIN 
    c.subject s 
WHERE 
    s.id = :subject 
    AND 
    s.customer_id = :customer

考虑通过最终添加这样的逻辑来为项目做出贡献:它可以合并到新的2.4系列中。