我有一个MySQL数据库的Doctrine2问题:
我有一个模型User
和一个型号Documents
。每个User
可能具有0或N Documents
。每个Document
分配给一个User
。我的模型:
用户
<?php
namespace Entity;
/**
* @Entity(repositoryClass="EntityRepositoryUserRepository")
* @Table(name="user")
*/
class User extends Object
{
/**
* @Id @GeneratedValue(strategy="UUID")
* @Column(type="string", length=36)
* @var string
*/
protected $id;
/**
* @OneToMany(targetEntity="EntityDocument", mappedBy="user")
*/
private $documents;
public function __construct($options = array())
{
$this->documents = new DoctrineCommonCollectionsArrayCollection;
}
}
文档
<?php
namespace Entity;
/**
* @Entity(repositoryClass="EntityRepositoryDocumentRepository")
* @Table(name="document")
*/
class Document extends Object
{
/**
* @Id @Column(type="string")
* @var string
*/
protected $id;
/**
* @ManyToOne(targetEntity="EntityUser", inversedBy="documents")
* @JoinColumn(name="user_id", referencedColumnName="id")
* @var User
*/
private $user;
}
现在,我想获得给定Document
ID的User
。SQL-Query将是:
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', DoctrineORMQueryExprJoin::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 EntityDocument used in join path expression but was not defined before.
而不是使用:
->innerJoin('\Entity\Document', 'd', DoctrineORMQueryExprJoin::ON, 'd.user_id = u.id')
尝试使用以下方式:
->innerJoin('u.documents', 'd', DoctrineORMQueryExprJoin::ON, 'd.user_id = u.id')
这是因为学说需要知道user
中的哪个字段必须加入documents
。了解现场学说将获取目标实体,而Doctine直接知道课程。