![](/img/trans.png)
[英]Doctrine innerjoin on “one to many” relationship with querybuilder
[英]Symfony Doctrine One to many querybuilder
我在學院和學院的課程之間有一對多的關系。
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行,'ic INNER JOIN'附近的col 170:錯誤:'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')
只需刪除這些行,就可以了。 存儲庫已經為您做到了。
嘗試這個:
(編輯)
$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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.