Имам User
обект със самопрепращаща се връзка "един към много" - Всеки User
притежава набор от ученици (които също са потребители):
<?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;
}
// ....
}
Съпоставянето се извършва като еднопосочно едно към много с таблица за присъединяване
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: { }
Сега, когато добавя/редактирам потребител с помощта на пакета EasyAdmin, мога да добавя учениците за този потребител. Когато обаче извлека обекта, свойството students е винаги null. Например, когато преглеждам списъка с потребители:
Тук потребителят „sagarl3232“ се предполага, че е ученик на „sj“, но изгледът по-горе ясно показва, че свойството при извличане е нула.
Обектът е съхранен правилно в базата данни. Това означава, че таблицата за присъединяване има правилните стойности:
Защо Doctrine ми причинява това? Не трябва ли автоматично да хидратира ученическия масив?
SELECT ..., u0_.mentor_id AS mentor_id_17 FROM user u0_ WHERE u0_.id IN (?) ORDER BY u0_.id DESC Parameters: [ 0 => [ 0 => 8, 1 => 7, 2 => 6, 3 => 5, 4 => 1 ] ]
- person Sagar Limaye   schedule 22.07.2017$user->getStudents()
. - person Sagar Limaye   schedule 22.07.2017