php - Nested composite foreign keys as ID in Doctrine
one text
We are developing an online store in Symfony 5 and Doctrine 2 where multiple customers (called participants in this case) can participate in the same order item and share the cost. The following simplified class diagram demonstrates the domain model:
The pure object model works fine in unit tests, but you obviously need to persist the data to a database, which is why we need to introduce IDs.
Order
, Product
and Participant
are entities with their own ID. In an ideal world, OrderItem
and OrderItemParticipation
would not need their own ID but be identified by the related entities they belong to, meaning their ID would be a composite foreign key.
So, an OrderItem
would by identified by the composite key of Order.id
and Product.id
, which is pretty much exactly the same as given in this example from the Doctrine 2 documentation: https://www.doctrine-project.org/projects/doctrine-orm/en/2.10/tutorials/composite-primary-keys.html#use-case-3-join-table-with-metadata.
Since OrderItemParticipation
relates to OrderItem
, which uses a composite key itself, it would need to use a nested composite key consisting of Order.id
, Product.id
and Participant.id
.
Unfortunately, Doctrine 2 doesn't seem to be able to work with nested composite keys as ID. I get this error
Column name
id
referenced for relation from App\Entity\OrderItemParticipation towards App\Entity\OrderItem does not exist.
when I try to generate a migration with the following mapping:
/** @ORM\Entity */
class OrderItem {
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity=Order::class, inversedBy="items")
*/
private Order $order;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity=Product::class)
*/
private Product $product;
// ...
}
/** @ORM\Entity */
class OrderItemParticipation {
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity=OrderItem::class, inversedBy="participations")
*/
private OrderItem $orderItem;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity=Participant::class)
*/
private Participant $participant;
// ...
}
So it seems that Doctrine is fine with my ID mapping in OrderItem
, but it struggles when it gets to OrderItemParticipation
. Is there a way to make Doctrine work with the given domain model? Is it maybe just an issue with the auto-generation of the migration, so if I had already manually set up the database, Doctrine might work with the given mapping? Or is the nested composite key ID approach too complicated for Doctrine?