从Doctrine2获取ManyToMany关系中的数据

时间:2014-12-01 23:37:52

标签: php orm doctrine-orm doctrine relationship

我在教师表和组表之间有以下关系N:N,其中有第三个teachers_groups表。

我想列出老师带给我的老师教的所有小组(**相关**),但当我得到所有老师的回报时,$teacher->getClasses()是空的。

这是我的代码:

教师控制器:

namespace App\Controllers;

class TeacherController extends Controller
{
    public function index()
    {
        $this->teachers = $this->model->getRepository()->findAll();
        // Bring all teachers, but does not bring their groups
        // with $teachers->getGroups()
        foreach ($this->teachers as $teachers) {
            var_dump($teachers->getGroups()); die();
        }
    }
}

教师实体:

namespace App\Entities;

use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;

/**
 * @Entity
 * @Table(name="teachers")
 */
class Teacher
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     **/
    private $id;

    /**
     * @ManyToMany(targetEntity="Group", mappedBy="teachers")
     **/
    private $groups;

    public function __construct()
    {
        $this->groups = new ArrayCollection();
    }

    public function setGroups($groups)
    {
        $this->groups = $groups;
    }

    public function getGroups()
    {
        return $this->groups;
    }
}

群组实体:

namespace App\Entities;

use Doctrine\Common\Collections\ArrayCollection as ArrayCollection;

/**
 * @Entity
 * @Table(name="groups")
 */
class Group
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     **/
    private $id;

    /**
     * @ManyToMany(targetEntity="Teacher")
     * @JoinTable(name="teachers_groups",
     * joinColumns={@JoinColumn(name="id_group",referencedColumnName="id")},
     * inverseJoinColumns={@JoinColumn(name="id_teacher", referencedColumnName="id")}
     * )
     **/
    private $teachers;

    public function __construct()
    {
        $this->teachers = new ArrayCollection();
    }

    public function setTeachers($teachers)
    {
        $this->teachers = $teachers;
    }

    public function getTeachers()
    {
        return $this->teachers;
    }
}

1 个答案:

答案 0 :(得分:0)

在我看来,你没有在你的Doctrine注释中正确引用命名空间。

解决方案1:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\ManyToMany(targetEntity="Teacher")
 * @ORM\JoinTable(name="teachers_groups",
...

或解决方案2:

use Doctrine\ORM\Mapping\ManyToMany;
use Doctrine\ORM\Mapping\JoinTable;
...
/**
 * @ManyToMany(targetEntity="Teacher")
 * @JoinTable(name="teachers_groups",
...

换句话说,您的注释目前已被忽略。我很惊讶您的教师资料库甚至将教师课程视为一个实体。