Doctrine: How to define relationships

In this post we will review how to define Doctrine relationships, from one-to-one to many-to-many relationships.

One-to-One

To explain this relationship we do it with an example. We suppose that we have two entities (User and Email); when we define the Email entity we should add a ‘user_id‘ property (which is the foreign key) due to the User entity is the “owner” of the relationship, this means the User has an Email. We always need to identify the “owner” side and add the foreign key to the entity which belongs to the “owner” entity. When we use this relationship, Doctrine uses a hasOne method. Let’s see how to define it with yaml:

1
2
3
4
5
6
7
8
9
Email:
  columns:
    user_id: integer
    address: string(150)
  relations:
    User:
      local: user_id
      foreign: id
      foreignType: one

One-to-Many and Many-to-One

Now, let’s suppose we have the same User entity which can have many phone numbers (for that we have a Phonenumber entity). We should follow the same convention than in the one-to-one relationship and define the foreign key in the Phonenumber entity, which belongs to the User entity. When we define this kind of relationship Doctrine uses the hasOne method for the Phonenumber entity and the hasMany method for the User entity. Let’s see how to define it with yaml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
User:
  // Some properties definitions here
  relations:
    Phonenumbers:
      type: many
      class: Phonenumber
      local: id
      foreign: user_id

Phonenumber:
  columns:
    user_id: integer
    phonenumber: string(50)
  relations:
    User:
      local: user_id
      foreign: id

Many-to-Many

And last but not least, when we need to define a many-to-many we have the need to add an extra table :-S, called JOIN table. Following with our User entity, let’s suppose we have a new entity called Group, and we know that a User can belong to a many Groups and that a Group can have a lot of Users. In this case, if we remove an User we should not remove the Group, but yes the relationship. When we define this kind of relationship Doctrine uses the hasMany method in both entities. Let’s see how to define it with yaml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
User:
  // Some properties definition here
  relations:
    Groups:
      class: Group
      local: user_id
      foreign: group_id
      refClass: UserGroup

Group:
  tableName: groups
  columns:
    name: string(30)
  relations:
    Users:
      class: User
      local: group_id
      foreign: user_id
      refClass: UserGroup

UserGroup:
  columns:
    user_id:
      type: integer
      primary: true
    group_id:
      type: integer
      primary: true

Well, I hope this post will be helpful to understand and know how to define Doctrine relationships.

Ref: Doctrine documentation