Reputation: 49
I have a User
entity with a self-referencing one-to-many relationship - Every User
owns a set of students (who are also users):
<?php
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*/
class User extends BaseUser
{
/**
* @var int
*/
protected $id;
private $students;
// ....
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
public function __construct() {
$this->students = new ArrayCollection();
// ...
parent::__construct();
}
/**
* Remove student
*
* @return User
*/
public function removeStudent($student)
{
$this->students->removeElement($student);
return $this;
}
/**
* Add a student
*
* @param User $students
*
* @return User
*/
public function addStudent($student)
{
$this->students->add($student);
return $this;
}
/**
* Get students
*
* @return User
*/
public function getStudents()
{
$this->students;
}
/**
* Set students
*
* @param User $students
*
* @return User
*/
public function setStudents($students)
{
$this->students = $students;
return $this;
}
// ....
}
The mapping is done as a one-to-many unidirectional with join table
AppBundle\Entity\User:
type: entity
table: null
repositoryClass: AppBundle\Repository\UserRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
// ...
manyToMany:
students:
targetEntity: User
joinTable:
name: mentors_students
joinColumns:
mentor_id:
referencedColumnName: id
inverseJoinColumns:
student_id:
referencedColumnName: id
unique: true
lifecycleCallbacks: { }
Now when I add/edit a user using the EasyAdmin bundle, I can add the students for that user. However, when I retrieve the entity, the students property is always null. For example, when I view the list of users:
Here the user 'sagarl3232' is supposed to be a student of 'sj' but the view above clearly shows the property when retrieved is null.
The entity is persisted correctly in the database. That is, the join table has the right values:
Why is Doctrine doing this to me? Isn't it supposed to hydrate the students array automatically?
Upvotes: 0
Views: 428
Reputation: 3312
Your getter doesnt return anything!
/**
* Get students
*
* @return User[]
*/
public function getStudents()
{
return $this->students;
}
BTW why you should adjust the docblock too. The getter is supposed to return an array User[]
Upvotes: 1