2014-12-01 55 views
0

我在教师表和组表之间存在以下关系N:N,其中存在第三个teachers_groups表。获取来自与Doctrine2的ManyToMany关系的数据

我想列出老师给我带来的这个老师教的所有小组(**是相关**),但是当我得到所有老师的回报时,$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; 
    } 
} 
+0

我不知道它是否是团队教师中缺少的'inversedBy =“groups”'。如果添加它没有帮助,可以在'return $ this-> conn-> executeQuery($ sql,$ params,$ types)之前在'BasicEntityPersister :: getManyToManyStatement()'中打印'$ sql';'看看是什么继续。 – 2014-12-03 11:59:10

回答

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", 
... 

换句话说,你的注解目前被我们忽略。我很惊讶你的教师存储库甚至将教师课程视为一个实体。

+0

我遵循他们自己的文档的例子:**'http://doctrine-orm.readthedocs.org/en/latest/reference/advanced-configuration.html'**。在没有问题的情况下,我的实体,包括其他有1:1关系的粗俗学生和班级。注释是可以的。除非遗漏关系。 – LeoFelipe 2014-12-02 23:44:54