doctrine many to one

I have two tables. I want to set up a one-to-many relationship, but also a many-to-one relationship.

A Page can have one Background — this is the background of the page.

A Page can also have many Backgrounds — this is a collection of user-uploaded backgrounds from which one will be chosen for the first relationship.

In other words, a user selects a background from a bunch of predefined backgrounds, or one of many backgrounds he has uploaded to try out.

edit: When deleting a background, I want all pages with that background_id to have background_id set to null. When deleting a page, I want all the custom backgrounds belonging to that page to be deleted.

Whilst doctrine and symfony allow the above configuration, when deleting the page Doctrine ignores cascade=»» on the Backgrounds property entirely, and of course an exception is raised when trying to delete the Page before deleting it’s custom Backgrounds.

This chapter explains mapping associations between objects.

Instead of working with foreign keys in your code, you will always work with references to objects instead and Doctrine will convert those references to foreign keys internally.

  • A reference to a single object is represented by a foreign key.
  • A collection of objects is represented by many foreign keys pointing to the object holding the collection

This chapter is split into three different sections.

  • A list of all the possible association mapping use-cases is given.
  • Association Mapping are explained that simplify the use-case examples.
  • Association Mapping are introduced that contain entities in associations.

One tip for working with relations is to read the relation from left to right, where the left word refers to the current Entity. For example:

  • OneToMany — One instance of the current Entity has Many instances (references) to the refered Entity.
  • ManyToOne — Many instances of the current Entity refer to One instance of the refered Entity.
  • OneToOne — One instance of the current Entity refers to One instance of the refered Entity.

See below for all the possible relations.

An association is considered to be unidirectional if only one side of the association has
a property referring to the other side.

To gain a full understanding of associations you should also read about owning and inverse sides of associations

Many-To-One, Un >

A many-to-one association is the most common association between objects. Example: Many Users have One Address:

The above @JoinColumn is optional as it would default to address_id and id anyways. You can omit it and let it use the defaults.

Generated MySQL Schema:

One-To-One, Un >

Here is an example of a one-to-one association with a Product entity that references one Shipment entity.

Note that the @JoinColumn is not really necessary in this example, as the defaults would be the same.

Generated MySQL Schema:

One-To-One, B >

Here is a one-to-one relationship between a Customer and a Cart . The Cart has a reference back to the Customer so it is bidirectional.

Here we see the mappedBy and inversedBy annotations for the first time. They are used to tell Doctrine which property on the other side refers to the object.

Note that the @JoinColumn is not really necessary in this example, as the defaults would be the same.

Generated MySQL Schema:

We had a choice of sides on which to place the inversedBy attribute. Because it is on the Cart , that is the owning side of the relation, and thus holds the foreign key.

One-To-One, Self-referencing

You can define a self-referencing one-to-one relationships like below.

Note that the @JoinColumn is not really necessary in this example, as the defaults would be the same.

With the generated MySQL Schema:

One-To-Many, B >

A one-to-many association has to be bidirectional, unless you are using a join table. This is because the «many» side in a one-to-many association holds the foreign key, making it the owning side. Doctrine needs the «many» side defined in order to understand the association.

This bidirectional mapping requires the mappedBy attribute on the «one» side and the inversedBy attribute on the «many» side.

This means there is no difference between a bidirectional one-to-many and a bidirectional many-to-one.

Note that the @JoinColumn is not really necessary in this example, as the defaults would be the same.

Generated MySQL Schema:

One-To-Many, Un >

A unidirectional one-to-many association can be mapped through a join table. From Doctrine’s point of view, it is simply mapped as a unidirectional many-to-many whereby a unique constraint on one of the join columns enforces the one-to-many cardinality.

The following example sets up such a unidirectional one-to-many association:

Generates the following MySQL Schema:

One-To-Many, Self-referencing

You can also setup a one-to-many association that is self-referencing. In this example we setup a hierarchy of Category objects by creating a self referencing relationship. This effectively models a hierarchy of categories and from the database perspective is known as an adjacency list approach.

Note that the @JoinColumn is not really necessary in this example, as the defaults would be the same.

Generated MySQL Schema:

Many-To-Many, Un >

Real many-to-many associations are less common. The following example shows a unidirectional association between User and Group entities:

Generated MySQL Schema:

Why are many-to-many associations less common? Because frequently you want to associate additional attributes with an association, in which case you introduce an association class. Consequently, the direct many-to-many association disappears and is replaced by one-to-many/many-to-one associations between the 3 participating classes.

Many-To-Many, B >

Here is a similar many-to-many relationship as above except this one is bidirectional.

The MySQL schema is exactly the same as for the Many-To-Many uni-directional case above.

Owning and Inverse S >

For Many-To-Many associations you can chose which entity is the owning and which the inverse side. There is a very simple semantic rule to decide which side is more suitable to be the owning side from a developers perspective. You only have to ask yourself which entity is responsible for the connection management, and pick that as the owning side.

Take an example of two entities Article and Tag . Whenever you want to connect an Article to a Tag and vice-versa, it is mostly the Article that is responsible for this relation. Whenever you add a new article, you want to connect it with existing or new tags. Your «Create Article» form will probably support this notion and allow specifying the tags directly. This is why you should pick the Article as owning side, as it makes the code more understandable:

This allows to group the tag adding on the Article side of the association:

Many-To-Many, Self-referencing

You can even have a self-referencing many-to-many association. A common scenario is where a User has friends and the target entity of that relationship is a User so it is self referencing. In this example it is bidirectional so User has a field named $friendsWithMe and $myFriends .

Generated MySQL Schema:

Mapping Defaults

The @JoinColumn and @JoinTable definitions are usually optional and have sensible default values. The defaults for a join column in a one-to-one/many-to-one association is as follows:

As an example, consider this mapping:

This is essentially the same as the following, more verbose, mapping:

The @JoinTable definition used for many-to-many mappings has similar defaults. As an example, consider this mapping:

This is essentially the same as the following, more verbose, mapping:

In that case, the name of the join table defaults to a combination of the simple, unqualified class names of the participating classes, separated by an underscore character. The names of the join columns default to the simple, unqualified class name of the targeted class followed by «\_id». The referencedColumnName always defaults to «id», just as in one-to-one or many-to-one mappings.

If you accept these defaults, you can reduce the mapping code to a minimum.

Collections

Unfortunately, PHP arrays, while being great for many things, are missing features that make them suitable for lazy loading in the context of an ORM. This is why in all the examples of many-valued associations in this manual we will make use of a Collection interface and its default implementation ArrayCollection that are both defined in the DoctrineCommonCollections namespace. A collection implements the PHP interfaces ArrayAccess , Traversable and Countable .

The Collection interface and ArrayCollection class, like everything else in the Doctrine namespace, are neither part of the ORM, nor the DBAL, it is a plain PHP class that has no outside dependencies apart from dependencies on PHP itself (and the SPL). Therefore using this class in your model and elsewhere does not introduce a coupling to the ORM.

Initializing Collections

You should always initialize the collections of your @OneToMany and @ManyToMany associations in the constructor of your entities:

The following code will then work even if the Entity hasn’t been associated with an EntityManager yet:

Do you prefer video tutorials? Check out the Mastering Doctrine Relations screencast series.

There are two main relationship/association types:

ManyToOne / OneToMany The most common relationship, mapped in the database with a foreign key column (e.g. a category_id column on the product table). This is actually just one association type, but seen from the two different sides of the relation. ManyToMany Uses a join table and is needed when both sides of the relationship can have many of the other side (e.g. «students» and «classes»: each student is in many classes, and each class has many students).

First, you need to determine which relationship to use. If both s >ManyToMany relation. Otherwise, you likely need a ManyToOne .

There is also a OneToOne relationship (e.g. one User has one Profile and vice versa). In practice, using this is similar to ManyToOne .

The ManyToOne / OneToMany Association¶

Suppose that each product in your application belongs to exactly one category. In this case, you’ll need a Category >Product object to a Category object.

Start by creating a Category entity with a name field:

This will generate your new entity class:

Mapping the ManyToOne Relationship¶

In this example, each category can be associated with many products. But, each product can be associated with only one category. This relationship can be summarized as: many products to one category (or equivalently, one category to many products).

From the perspective of the Product entity, this is a many-to-one relationship. From the perspective of the Category entity, this is a one-to-many relationship.

To map this, first create a category property on the Product >ManyToOne annotation. You can do this by hand, or by using the make:entity command, which will ask you several questions about your relationship. If you’re not sure of the answer, don’t worry! You can always change the settings later:

This made changes to two entities. First, it added a new category property to the Product entity (and getter & setter methods):

Оцените статью