Francis Straccia
Francis Straccia

Reputation: 916

Doctrine2 OneToMany with multiple Entities

I have three kinds of Users, every user has some FiscalData and is linked to a UserCredential entry.

Which translates in:

UserX (X=1,2,3) has two FKs referring to FiscalData and UserCredential tables.

Using Doctrine2, reading the docs http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/association-mapping.html, I believe to need the MappedSuperClass pattern.

I have also read the following questions:

Doctrine 2 - One-To-Many with multiple Entities

Many-To-One with multiple target entities

Doctrine2, Symfony2 - oneToOne with multiple entities?

But in the docs is clearly stated that

A mapped superclass cannot be an entity, it is not query-able and persistent relationships defined by a mapped superclass must be unidirectional (with an owning side only). This means that One-To-Many associations are not possible on a mapped superclass at all. Furthermore Many-To-Many associations are only possible if the mapped superclass is only used in exactly one entity at the moment. For further support of inheritance, the single or joined table inheritance features have to be used.

So, how to achieve what I'm trying to achieve, which is a bidirectional relationship between UserX and FiscalData/UserCredential? (so that f.e. via Doctrine I can get a UserCredential and check what kind of profiles it has associated)

Any complete minimal code example showing how to enforce the relationship I'm looking for (and not just the MappedSuperClass inheritance shown in the docs will be highly appreciated.

Upvotes: 1

Views: 2276

Answers (1)

timdev
timdev

Reputation: 62924

Use an abstract entity instead of MappedSuperClass. Single-table is usually the way to go unless you're sure you want class/table.

<?php
/**
 * @ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({
 *     "mentor" = "Mentor",
 *     "protege" = "Protege"
 * })
 */
abstract class User { ... }

Upvotes: 0

Related Questions