Model That Links To Any Another Model

Hi.

On my site everything can be commented (videos, articles, posts, other comments, whatever), 14 different models. All comments are governed by Comment model. The question is: how do I specify association between Comment and all other models? Adding 14 foreign keys is definitely not an option, same as bunch of intermediary tables. Also please note that I don’t want to make a virtual relation (make get/setComments methods for each model or through behavior with own code that’ll load/save comments).

Maybe then you shouldn’t have 14 models, but just one?

If you want cascade deleting (deleting a video will delete the comments) you have 2 options:

  • the simpliest is to add 14 fk, no preformance concerns, noone cares.

  • make specification of table:

a table ‘commentable’ with at least the only id

comments has a fk on commentable

all your entities has a fk on commentable

eg: video: id, commentable_id, other fields.

In this way you have to delete the related commentable for cascade deleting all records, also the comment, deletecomment action will work on the same model, wich simplifies a lot.

I prefer the method with 14 fk, by the way.

Seems thats what I’ll have to do :( I can say only that this solution is definitely a dirty hack. Thanks for responses people.