Question

I have Students, Classrooms and Student_Classroom tables.

Students:

 - ID  
 - Name  
 - Year_born  

Classroom:

 - ID  
 - Name  
 - Number  
 - Floor  

Student_Classroom:

 - ID
 - ID_Student
 - ID_Classroom

How should it be done using Symfony2 and Doctrine? Using annotations.

Was it helpful?

Solution

It looks like a very simple n:m relation to me. Therefore your 2 entities should look something like this:

/** 
 * @ORM\Entity
 */
class Student
{
    /** 
     * @ManyToMany(targetEntity="Classroom")
     */
    private $classrooms;

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

and

/**
 * @ORM\Entity
 */
class Classroom
{
    /** 
     * @ManyToMany(targetEntity="Student")
     */
    private $students;

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

Make sure you add the required use statements to the top of both entity class files. Doctrine will automatically generate the n:m join table itself and handle all needed relations. Read more about n:m relations in the doctrine documentation. Also checkout this Q&A on SO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top