OneToMany关系中的Doctrine2查询错误

时间:2012-11-05 10:01:11

标签: php mysql doctrine-orm

我对MySQL数据库有一个doctrine2问题:

我有一个模型User和一个模型Documents。每个User可能有0或n Documents。每个Document只分配给一个User。我的模特:

用户

<?php

namespace Entity;

/**
* @Entity(repositoryClass="Entity\Repository\UserRepository")
* @Table(name="user")
*/
class User extends Object
{
    /**
    * @Id @GeneratedValue(strategy="UUID")
    * @Column(type="string", length=36)
    * @var string
    */
    protected $id;

    /**
    * @OneToMany(targetEntity="\Entity\Document", mappedBy="user")
    */
    private $documents;

    public function __construct($options = array())
    {
        $this->documents = new \Doctrine\Common\Collections\ArrayCollection;
    }
}

文档

<?php

namespace Entity;

/**
* @Entity(repositoryClass="Entity\Repository\DocumentRepository")
* @Table(name="document")
*/
class Document extends Object
{
    /**
    * @Id @Column(type="string")
    * @var string
    */
    protected $id;

    /**
    * @ManyToOne(targetEntity="\Entity\User", inversedBy="documents")
    * @JoinColumn(name="user_id", referencedColumnName="id")
    * @var User
    */
    private $user;
}

现在我想获得给定User ID的Document。 SQL查询将是:

SELECT u.*
FROM `user` u
INNER JOIN `document` d ON d.user_id = u.id
WHERE d.id = 'mydocumentid'

但这不起作用:

$user = $queryBuilder
        ->select('u.*')
        ->from('\\Entity\\User', 'u')
        ->innerJoin('\\Entity\\Document', 'd', \Doctrine\ORM\Query\Expr\Join::ON, 'd.user_id = u.id')
        ->where('d.id = :documentId')
        ->setParameter('documentId', 'mydocumentid')
        ->setMaxResults(1)
        ->getQuery()
        ->getSingleResult();

直接查询也不起作用:

$query = $em->createQuery('
    SELECT
        u.*
    FROM
        Entity\\User u
    INNER JOIN
        Entity\\Document d ON d.user_id = u.id
    WHERE
        d.id = "mydocumentid"
');

你能帮助我帮忙吗?

错误消息

[Semantical Error] line 0, col 66 near 'd ON d.user_id': Error: Identification Variable \Entity\Document used in join path expression but was not defined before.

1 个答案:

答案 0 :(得分:3)

而不是使用:

->innerJoin('\\Entity\\Document', 'd', \Doctrine\ORM\Query\Expr\Join::ON, 'd.user_id = u.id')

尝试使用:

->innerJoin('u.documents', 'd', \Doctrine\ORM\Query\Expr\Join::ON, 'd.user_id = u.id')

这是因为Doctrine需要知道user必须加入documents中的哪个字段。知道字段Doctrine将获取目标实体,Doctine直接知道该类。