我认为我的问题不明确,但我试着在这里说明我的观点.假设我有一个多对多的自我引用关系,用户可以成为一名教师(比如你在SO发布答案),教师也可以是学生(你可以回答问题,但也可以提问).
namespace Entities;
/** @Entity @Table(name="users")) */
class User {
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Column(type="string", length="30")
*/
private $name;
/**
* @ManyToMany(targetEntity="User", inversedBy="teachers")
* @JoinTable(name="Teachers_Students",
* joinColumns={@JoinColumn(name="teacher", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="student", referencedColumnName="id")}
* )
*/
private $students;
/**
* @ManyToMany(targetEntity="User", mappedBy="students")
*/
private $teachers;
function getName() {
return $this->name;
}
function setName($name) {
$this->name = $name;
}
function getStudents() {
return $this->students;
}
function getTeachers() {
return $this->teachers;
}
}
$user1 = new User;
$user1->setName("user 1");
$user2 = new User;
$user2->setName("user 2");
$user3 = new User;
$user3->setName("user 3");
$user4 = new User;
$user3->setName("user 4");
我喜欢在他们之间设置师生关系,我正在阅读doctrine reference,看到你可以使用Collections :: add()将元素添加到集合中
// user1 is a teacher to user2 & 3
$user1->getStudents()->add($user2);
$user1->getStudents()->add($user3);
// user2 is a teacher to user3
$user2->getStudents()->add($user3);
// user4 is a student to user2
// tests if adding something from the inverse side works
$user4->getTeachers()->add($user2);
但这失败了
Fatal error: Call to a member function
add() on a non-object in
D:\ResourceLibrary\Frameworks\Doctrine\tools\sandBox\index.PHP
on line 70
如何将元素添加到集合或关系中?
解决方法:
请记住,您的集合变量只是常规的ol’类属性.这意味着在初始化它们之前它们将为空.通常要做的是使用Doctrine的ArrayCollection类来实例化它们,这将允许您使用您描述的方法.
试试这个:
public function __construct()
{
$this->students = new \Doctrine\Common\Collections\ArrayCollection();
$this->teachers = new \Doctrine\Common\Collections\ArrayCollection();
}