Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine polymorphic association

Tags:

doctrine

I have a table named forums with the follow field structure:

  1. object_type --> [ Group | Page | Tournament | etc....] (Possibles values. each element has its own table)

  2. object_id --> [group's id | page's id | tournament's id | etc..] (id object_type)

  3. id_forum, 4.name, etc.

Then I have the following tables: Group, Page, Tournament, etc..

Is it possible implement this with doctrine?

like image 713
aprencai Avatar asked Jan 31 '11 17:01

aprencai


2 Answers

This should have been a comment but my reputation is too low, sorry.

Unfortunately polymorphic association is not exactly the same as CTI (Class Table Inheritance) : CTI requires a parent table with the same id for all subclasses.

CTI might work in most cases, but it can be a problem if you want to create a polymorphic association between existing entities that already have their own id and/or possibly might have a different id type.

Besides CTI requires to create a record in the parent table for each subclass which is useless for a polymorphic association. A polymorphic association should not require any table, it should just join existing tables with (id, type) conditions. I suppose Doctrine requires a parent table for simplicity/performance reasons.

When CTI is not a solution, I suggest to emulate the polymorphic association at the Repository level, i.e. create an abstract Repository with a $type attribute and implement a polymorphicJoin method that would automatically join the current query to the target table with the id/type conditions. Then extends the abstract Repository with your subclasses Repositories and call the polymorphicJoin method when needed in your find/select methods.

It would be awesome if that kind of association was implemented in Doctrine.

like image 71
Mathieu Bautista Avatar answered Sep 17 '22 23:09

Mathieu Bautista


I think what you are looking for can be done with inheritance.

Check http://www.doctrine-project.org/docs/orm/2.0/en/reference/inheritance-mapping.html for detailed explanation.

like image 45
Hakan Deryal Avatar answered Sep 17 '22 23:09

Hakan Deryal