我假設您已在您的實體中定義了Teacher
和Student
之間的關係。在這種情況下,您可以通過調用$teacher->getStudents()
來獲取Student
對象(假設您已在Teacher
實體類中定義了這種方法)。見Doctrine documentation about association mapping
例如,對於一個一對多的關係:
$query = $em
->createQueryBuilder('t')
->from('AppBundle:Teacher','t')
->join('AppBundle:Student','s')
->select(array('t', 's'))
->where('t.id=id and s.tid=tid')
->getQuery()
->getResult();
}
:
<?php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Teacher
{
// ...
/**
* One Teacher has Many Students.
* @OneToMany(targetEntity="Student", mappedBy="teacher")
*/
private $students;
// ...
public function __construct() {
$this->students = new ArrayCollection();
}
}
/** @Entity */
class Student
{
// ...
/**
* Many Students have One Teacher.
* @ManyToOne(targetEntity="Teacher", inversedBy="students")
* @JoinColumn(name="teacher_id", referencedColumnName="id")
*/
private $teacher;
// ...
}
在QueryBuilder
對象,你可以通過添加類似的東西,避免對$teacher->getStudents()
調用額外查詢的需要
如果您的實體中的Teacher
和Student
之間存在上述關係,您甚至可以簡化連接:
$query = $em
->createQueryBuilder('t')
->from('AppBundle:Teacher','t')
->join('t.students', 's')
->select(array('t', 's'))
->getQuery()
->getResult();
}
Furthmore你並不需要,如果你通過TeacherRepository
對象創建QueryBuilder
對象調用from()
方法:
$query = $teacher
->createQueryBuilder('t')
->join('t.students', 's')
->select(array('t', 's'))
->getQuery()
->getResult();
}
取意見,我不認爲像預期的那樣的'createQueryBuilder的第一個參數,這將工作( )'方法只是定義了應該填充的實體的別名。有關可能的解決方案,請參閱以下答案。 – W0rma