学说不尊重自我引用关系

时间:2017-07-21 20:01:29

标签: symfony doctrine-orm symfony2-easyadmin

我有一个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;
    }
    // ....
}

映射以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: {  }

现在,当我使用EasyAdmin软件包添加/编辑用户时,我可以为该用户添加学生。但是,当我检索实体时,students属性始终为 null 。例如,当我查看用户列表时:

enter image description here

这里用户'sagarl3232'应该是'sj'的学生,但上面的视图清楚地显示了检索时属性为null。

实体在数据库中正确保留。也就是说,连接表具有正确的值:

enter image description here

为什么Doctrine这样对我?是不是应该自动给学生阵列补水?

1 个答案:

答案 0 :(得分:1)

你的获取者不会返回任何东西!

/**
 * Get students
 *
 * @return User[]
 */
public function getStudents()
{
    return $this->students;
}

BTW为什么你也应该调整docblock。 getter应该返回一个数组User []