Reputation: 4130
I'm using Doctrine 2 in Zend.
I'm trying to figure out how to access the properties/method for related models from the current object.
For example, we have two tables: Schools and Students.
Many Students belong to a school, so this is a many to one relationship and I'm only interested in listing all the students for each school. I do not wish to query student records to find the details of the school they belong to therefore this is classed as a unidirectional relationship.
Now to set up the many to one relationship in Doctrine 2 between the tables I'd add this in the Students entity, as it is the owning side:
/**
* @ManyToOne(targetEntity="Schools")
* @JoinColumn(name="school_id", referencedColumnName="school_id")
*/
private $schoolId;
Where the name values correspond the column names in the students table and schools table respectively.
So if I have an object of a Schools record, how do I access the student properties/methods?
echo $oSchool->Students->getName(); // doesn't work
I can't understand what I have done wrong, the proxy class is being generated. Appreciate it if anyone could point me in the right direction.
Upvotes: 3
Views: 7555
Reputation: 203
For those who are facing this issue: "Fatal error: Call to a member function setValue() on a non-object in C:\xampplite\htdocs\test\library\Doctrine\ORM\PersistentCollection.php on line 168 –"
Solution: Need to replace mappedBy value with doctrine property value instead of Table column name
Ex:
Correct Syntax: @ORM\OneToMany(targetEntity="Test\Entity\School", mappedBy="school")
Wrong Syntax: Correct syntax: @ORM\OneToMany(targetEntity="Test\Entity\School", mappedBy="school_id")
Upvotes: 1
Reputation: 129
In the Schools entity you'd want to have something like this
/**
* @param \Doctrine\Common\Collections\Collection $property
* @OneToMany(targetEntity="Students", mappedBy="school")
*/
private $student;
public function __construct() {
$this->student = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getStudent() {
return $this->student;
}
With this you could do something like the following, which gives you an ArrayCollection with all student objects
$studentsArray = $school->getStudent();
Hope that helps... Docrine 2 is very powerful but some things are not documented very well. Some more information on this in the Documentation at Working with Assiciations.
Upvotes: 6
Reputation: 4130
I've made some progress. I read the 'Working with Objects' section of Doctrine 2's documentation.
Associated objects can be accessed by something like this (according to the example given in my question):
$oStudent->getSchoolId()->getName(); // gets a student's school's name by traversing the school class
However in my orignal question, I wanted to access the students belonging to a school via the schools object. I am completely stumped on how to do this, It seems to me its not possible.
Upvotes: 0