Search code examples
databasesymfonydoctrine-orm

How can I use 'foreign key' on doctrine?


I am making the lesson administration system on symfony2 and doctrine

I am confused to use foreign key in doctrine.

/Entity/User.php

class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     *@ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\Lesson", inversedBy("teacher"))
     */
    protected $id;
    .
    .
}

/Entity/Lesson.php

class Lesson
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    /**
     *
     * @ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\User", inversedBy("id"))
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $teacher;
    .
    .
}

Each 'Lesson' has one teacher registered in User.php.

How can I write annotation for this purpose?

I am also planning that each Lesson has multiple students from /Entity/User. How can I write annotation for this purpose? (ManyToMany?)

I have researched ,but I couldn't find good documents for doctrine annotation.


Solution

  • Here some cheat sheets for doctrine annotations : link

    For your problem, you need to define your variables in each side of your associations.

    In Lesson.php :

    /**
     * @ORM\OneToOne(
     *     targetEntity="Acme\UserBundle\Entity\User", 
     *     inversedBy="lessons*removethis : name of the variable in user.php*"
     * )
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $teacher;
    

    In User.php :

    /**
     * @ORM\OneToOne(
     *     targetEntity="Acme\UserBundle\Entity\Lesson", 
     *     mappedBy="teacher*removethis : name of the variable in lesson.php*"
     * )
     */
    private $lessons;
    

    And yes, ManyToMany is good for the purpose your are looking for :)