Symfony: ManyToOne and Migration
Created at: 2023-05-17
Lately I had to migrate a csv and create the entity relative to them. I import them using the Id given by the csv, with the Id that when creating a ManyToOne relation I would spare some time.
Doctrine ManyToOne
Doctrine ManyToOne Relation allow to make a n..1 relation in your database, a common relation in mysql, see the Symfony explication.
In order to define, you can use Doctrine annotation:
or, when you are using symfony maker bundle, you can create automatically the annotation. Using the make bundle will automatically produce the oppposite relations: OneToMany.
you can pass some parameters when creating a ManyToOne Relation:
inversedBy:
cascade:
fetch:
Avoid findOneById
3 functions may be used in order to retrieve/emulate a relation in doctrine:
- find: retrieve an entity by peforming a findBy
- getReference: if the entity is already loaded, this will directly return the entity, otherwise, it will use the find functionality to give the entity.
- getPartialReference: for migrationstuff, this one is the one that we need, it creates a entity, with only the id, thus, in order to avoid creating a database request.
I had then a partial test: same request: creating the manyToOneRelation, using the three different types
- operation finds have been performed with
find: 145 ms
getReference: 117 ms
getPartialReference: 104 ms.
Reducing the overall time by 40ms.
there is a functionality in doctrine, called getReference:
To be considered
this functionality will throw errors, when the target entity does not exist, this could happen during the following cases:
- data insconsitency: the data you are migrating are faulty
- the relative entity is not created when you insert the new entity.
back to list