I have CakePHP app in which I’d like to attach gallery to multiple resources. Let’s say I’ve got artists, each one has own gallery. I’ve got articles, every article has some images attached to it and so on. Now I set up tables like this:
- Artists hasMany Artistimages, fields in
artistimagestable are:id, artist_id, filename, filetype, filesizeetc. - Articles hasMany Articleimages, fields in
articleimagestable are:id, article_id, filename, filetype, filesizeetc.
…but this is not how it should be, I think.
Is there possibility to have one table called for example uploads which will contain all images with foreign key pointing to resource its reffering to? How to tell CakePHP which image is coming from which resource?
I’d recommend using the Polymorphic Behavior. I often do this for a
Binarymodel which covers images, documents, etc. These represent the physical files that can be associated with any number of models (photos, applicants, etc.).The gist of a polymorphic relationship is that the table has 2 additional fields. One field that indicates the name of the model being associated (e.g.
Photo,Applicant, etc.) and another for the foreign key value (i.e. theidfield in thephotostable, for example).