nielsv
nielsv

Reputation: 6810

ManyToOne relationship + How to use in both directions

I have 2 tables like this:

Users
    - UserID
    - Username
    - Password
    - ...
 Players
    - playerID
    - playerName
    - ...
    - User

The relation is ManyToOne (see the picture) and it's not required.

enter image description here

I've generated my entities automatically with Doctrine. In my player Entity I have:

 /**
 * @var \NV\VolleyScoutBundle\Entity\Users
 *
 * @ORM\ManyToOne(targetEntity="NV\VolleyScoutBundle\Entity\Users")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="user_id", referencedColumnName="user_id")
 * })
 */
protected $user;

But I don't have a $player variable in my Users Entity. In what way can I add this? Tried to do this but gave me different errors. What I'm trying to do is add a player form to my register form.

So in my RegisterType (=form) I woud like to add ->add('player', new PlayerType()). But that's not possible without a $player variable in my Users entity.

What type of relation do I need to setting for $player in my Users entity?

Upvotes: 0

Views: 53

Answers (1)

Matzach
Matzach

Reputation: 26

You have to add annotation in user entity.

In Player Enity

@ORM\OneToMany(targetEntity="Players", mappedBy="user")
protected $player;

In User Entity:

@ORM\ManyToOne(targetEntity="Users", inversedBy="player")
@ORM\JoinColumn(name="user_id", referendecColumn="UserId")
proteced $user;

This is only a draft. You have to write full namespaces for target entities, and correct errors if there are some.

A lot of setails you can find here: Doctrine documentation - working with association

Try to use small caps for table names, because MySQL under linux doesn't like uppercaps. $player must be instance of ArrayCollection

Upvotes: 1

Related Questions