我遇到ManyToMany关联问题。我无法弄清楚如何从数据库中获取数据。 我有2个实体 - 教师和主题。
课程科目
/**
*
* @ORM\ManyToMany(targetEntity="Teacher", mappedBy="subjects")
*/
private $teachers;
public function __construct() {
$this->teachers = new ArrayCollection();
}
/**
* Add teacher
*
* @param \AppBundle\Entity\Teacher $teacher
*
* @return Subject
*/
public function addTeacher(\AppBundle\Entity\Teacher $teacher)
{
$this->teachers[] = $teacher;
return $this;
}
/**
* Remove teacher
*
* @param \AppBundle\Entity\Teacher $teacher
*/
public function removeTeacher(\AppBundle\Entity\Teacher $teacher)
{
$this->teachers->removeElement($teacher);
}
/**
* Get teachers
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTeachers()
{
return $this->teachers;
}
实体老师
班主任
/**
*
* @ORM\ManyToMany(targetEntity="Subject", inversedBy="teachers")
*/
private $subjects;
public function __construct()
{
$this->subjects = new ArrayCollection();
}
/**
* Add subject
*
* @param \AppBundle\Entity\Subject $subject
*
* @return Teacher
*/
public function addSubject(\AppBundle\Entity\Subject $subject)
{
$this->subjects[] = $subject;
return $this;
}
/**
* Remove subject
*
* @param \AppBundle\Entity\Subject $subject
*/
public function removeSubject(\AppBundle\Entity\Subject $subject)
{
$this->subjects->removeElement($subject);
}
/**
* Get subjects
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getSubjects()
{
return $this->subjects;
}
我想要做的就是从教师+与他们相关的主题中获取所有信息。
我的控制器看起来应该怎么做?
我尝试通过
来做到这一点 $teacher = $this->getDoctrine()->getRepository(Teacher::class)->findAll();
return $this->render('admin/adminDashboard.html.twig', [
'teachers' => $teacher]);
但我仍然有错误
答案 0 :(得分:0)
首先,我的建议是将$ teacher变量改为$ teacher findAll()方法返回一个数组,因此你必须遍历它。在您的控制器中:
Signature rsa = Signature.getInstance("SHA1withRSA");
rsa.initSign(getPrivate(“<RSAKeyValue><Modulus>oQRshGhLf2Fh...”));
rsa.update(message.getBytes());
byte[] signed = rsa.sign();
在你的树枝模板中:
foreach($teachers as $teacher) { // Here you have $teacher and you can do $teacher->getSubjects() }
如果这不起作用,请告诉我们你会得到什么样的错误。 这都假设您在数据库中有条目,或者从您获取实体的任何地方开始。
答案 1 :(得分:0)
如果{% for t in teachers %}{{dump(t.subjects.count)}}{% endfor %}
有效,则表示数据存在。
如果你的意思是{{teacher.subjects}}
抛出错误:在渲染模板期间抛出异常(“Catchable Fatal Error:类Doctrine \ ORM \ PersistentCollection的对象无法转换为字符串如果您以前从未见过这个错误,请仔细阅读:
类Doctrine \ ORM \ PersistentCollection 的对象引用subjects
,它作为一个集合,不能像字符串一样被抛入html标记。
取决于您希望如何呈现数据,但基本要素是:
{% for t in teachers %}
<tr>
{% for s in t.subjects %}
<td>s.getName</td>
{% endfor %}
</tr>
{% endfor %}
假设subject
实体有一个属性name
和一个getter。希望你得到要点。
让我知道