Tutorial :Doctrine: How do i add elements to a relationship



Question:

i think my question is not clear but i try to illustrate my point here. assuming i have a many to many, self referencing relationship where a user can be a teacher (say u post answers at SO) and a teacher can be a student (u may answer questions but may ask too) too.

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;      }  }  

say i have a few users

$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");  

and i like to setup teacher-student relationships between them, i was reading up doctrine reference, saw that u can use the Collections::add() to add elements to a collection

// 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);  

but this fails with

Fatal error: Call to a member function add() on a non-object in D:\ResourceLibrary\Frameworks\Doctrine\tools\sandbox\index.php on line 70

how can i add elements to a collection or a relationship?


Solution:1

Remember that your collection variables are just regular ol' class properties. Which means they'll be null until you initialize them. The typical thing to do is instantiate them using Doctrine's ArrayCollection class, which will allow you to use the methods you described.

Try this:

public function __construct()  {     $this->students = new \Doctrine\Common\Collections\ArrayCollection();     $this->teachers = new \Doctrine\Common\Collections\ArrayCollection();    }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »