Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Doctrine ORM : Joined table inheritance

Related to this previous topic : Database : Account table with Joined Tables Inheritance

I’ve created a joined tables inheritance in my database (MySQL) :
enter image description here

client_id attributes are both PK and FK.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now I need to represent it with Doctrine ORM but I can’t find a solution of how to make that.

I created, with Symfony commands, the Client entity and for the ClientCompany entity I don’t know which relationship to use nor how to use the Client ID as primary key of the CompanyClient entity.

Does anyone know how to do it?

>Solution :

First of all, be really carefull with inheritance, this is a really good feature of doctrine but need to be used with a lot of cautious because of it’s counterpart.

For your case, i would advise to not try to put "person" and "company" under the same abstract "client" class for conception reason i already explain in this answer since a company and a person are totally different things: Symfony 6 inheritance Mapping : How to submit a form depends on a clicked radio button?

But i will still answer on how to properly do a join table inheritance :

AbstractClient.php

#[Entity]
#[InheritanceType('JOIN_TABLE')] 
#[DiscriminatorColumn(name: 'discr', type: 'string')]
#[DiscriminatorMap(['person' => Person::class, 'company' => Company::class])]
abstract class Client
{
    // you do not need clientType since it is hold by the "discr" column
    // And if you want to know what type your client is you can do it using   
    // if($client instanceof Person::class) { do something}
}

Person.php

#[Entity]
class Person extends Client
{
    // ...
}

Company.php

#[Entity]
class Company extends Client
{
    // ...
}

Take a look at #[InheritanceType('JOIN_TABLE')]
It will create one table for each entity and they will share ids.
If you create a company with id 2, there will be a client with id 2. So a Person with id 2 will never be possible.

But if you use 'SINGLE_TABLE' it will create only one table with all the field of all the entity which will be empty depending on which child you inserted inside.

But again i strongly advise you to not use join table inheritance for your usecase

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading