Php Symfony原则一对多查询生成器
学院和学院课程之间有一对多的关系Php Symfony原则一对多查询生成器,php,symfony,doctrine-orm,doctrine,query-builder,Php,Symfony,Doctrine Orm,Doctrine,Query Builder,学院和学院课程之间有一对多的关系 class Institutes { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\OneToMany(targetEntity="PNC\I
class Institutes {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="PNC\InstitutesBundle\Entity\InstitutesCourses", mappedBy="institute", cascade={"all"})
* */
protected $inst;
}
class InstitutesCourses {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="PNC\InstitutesBundle\Entity\Institutes", inversedBy="inst")
* @ORM\JoinColumn(name="institute_id", referencedColumnName="id")
*/
protected $institute;
/**
* @ORM\ManyToOne(targetEntity="PNC\CoursesBundle\Entity\Courses", inversedBy="instituteCourses")
* @ORM\JoinColumn(name="course_id", referencedColumnName="id")
*/
protected $course;
}
我想把分配给一门课的所有课程都取出来。每个研究所都由一个用户拥有。我已经编写了这个运行良好的psql查询
SELECT ic.*
FROM institutes_courses ic
RIGHT JOIN institutes i ON i.id = ic.institute_id
WHERE i.user_id = 26;
id | institute_id | course_id |
-----+--------------+-----------+
389 | 21 | 51 |
390 | 21 | 53 |
391 | 21 | 52 |
像这样翻译成doctinre querybuilder
$repository = $em->getRepository('PNCInstitutesBundle:InstitutesCourses');
$query= $repository->createQueryBuilder('ic')
->select('ic')
->from('PNCInstitutesBundle:InstitutesCourses', 'ic')
->orderBy('ic.id', 'ASC')
// THE FOLLOWING LINE IS CRITICAL:
->JOIN('PNCInstitutesBundle:Institutes', 'i', 'WITH' ,'i.id=ic.institute')
->where('i.user = :user')
->setParameter('user', $this->getUser()->getId())
->getQuery();
上面说
[语义错误]第0行,第170列“ic内部联接”附近:错误:“ic”
已定义
新加入symfony2原则,无法找出问题所在。如果您查看
createQueryBuilder
的源代码,您将看到以下内容:
public function createQueryBuilder($alias, $indexBy = null)
{
return $this->_em->createQueryBuilder()
->select($alias)
->from($this->_entityName, $alias, $indexBy);
}
这意味着您不应该在代码中执行以下操作
->select('ic')
->from('PNCInstitutesBundle:InstitutesCourses', 'ic')
只要放下那几行就行了。存储库已经为您完成了此操作。请尝试以下操作:
(编辑)
在两行中,我得到了这个错误
无法计数查询,它从组件中选择了两个,无法进行区分
您对该查询执行count()
吗?您是否尝试通过执行$qb->getQuery()->getSQL()
和$qb->getQuery()->getDQL()
来查看生成的DQL和SQL是什么?在getDQL()
上是,我从PNC\InstitutesBundle\Entity\InstitutesCourses ic内部连接PNCInstitutesBundle:Institutes i WITH i.id=ic.institute WHERE i.user=:user'这几乎是我的原始psql。'无法计算从组件中选择两个的查询,无法区分'错误我们可以看到您的实体映射吗?谢谢,我没有工作。你能解释一下吗,我做错了什么。
$repository = $em->getRepository('PNCInstitutesBundle:InstitutesCourses');
$query= $repository->createQueryBuilder('ic')
->leftJoin('ic.institute', 'i')
->where('i.user = :user')
->setParameter('user', $this->getUser()->getId())
->orderBy('ic.id', 'ASC')
->getQuery();
$results = $query->getResult();