Doctrine polymorphic association
I have a table named forums
with the follow field structure:
object_type --> [ Group | Page | Tournament | etc....] (Possibles values. each element has its own table)
object_id --> [group's id | page's id | tournament's id | etc..] (id object_type)
id_forum, 4.name, etc.
Then I have the following tables: Group
, Page
, Tournament
, etc..
Is 开发者_如何学编程it possible implement this with doctrine?
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.
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.
I had a similar problem. I've posted a complete example on how to implement polymorphic associations in Doctrine 2.2 in this post.
精彩评论