I have one to many releationship between institute and institute courses.
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;
}
I want to fetch all courses assign to one courses. each institute is owned by a user. I have wrote this psql query that is working well
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 |
and translated into doctinre querybuilder like this;
$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();
and it says that,
[Semantical Error] line 0, col 170 near 'ic INNER JOIN': Error: 'ic' is already defined.
new to symfony2 doctrine, cant figure out what's wrong.
if you have a look at the source code of createQueryBuilder
you'll see the following:
public function createQueryBuilder($alias, $indexBy = null)
{
return $this->_em->createQueryBuilder()
->select($alias)
->from($this->_entityName, $alias, $indexBy);
}
Which means you should not do the following in your code.
->select('ic')
->from('PNCInstitutesBundle:InstitutesCourses', 'ic')
Just drop that lines and it should be ok. Repository already did it for you.
Try this:
(EDIT)
$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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.