14

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.

BenMorel
37.1k53 gold badges208 silver badges339 bronze badges
asked Apr 12, 2013 at 11:28

1 Answer 1

15

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

Alex Rashkov
10k3 gold badges35 silver badges57 bronze badges
answered Apr 12, 2013 at 11:43
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks.GreenLeaf it works well for my purpose, The given link is useful as well.
the link gives me a 404
I updated the link. Here is the complete link : elao.com/fr/blog/symfony-2-doctrine-2-cheat-sheets
Updated link is dead.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.