我有一个 MySQL 数据库的学说 2 问题:
我有一个模型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
给定Document
ID 的。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.