How can I use 'foreign key' on doctrine?

2019-04-20 17:19发布

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.

thanks a lot

1条回答
姐就是有狂的资本
2楼-- · 2019-04-20 18:04

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 :)

查看更多
登录 后发表回答