views:

131

answers:

3

Hi,

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:

  1. Artists hasMany Artistimages, fields in artistimages table are: id, artist_id, filename, filetype, filesize etc.
  2. Articles hasMany Articleimages, fields in articleimages table are: id, article_id, filename, filetype, filesize etc.

...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?

A: 

If this was me, I would have an images table, then I would have the Artist and Article hasAndBelongsToMany to Image.

Your HABTM would then have a two join tables artists_images and articles_images, then with any luck, Cake will write into these join tables the relationships between each. So you should end up with the correct things associated with the correct images.

By using the HABTM, you can even have one image associated with an Article and Artist, and the same image associated more than once if you need to.

Hope this makes sense, there is more info on HABTM in the book, http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM

DavidYell
Yeah I was thinking about that. But I'm still hoping for something simpler, with only one table. Thanks for answer, tho.
Mef
Well I mean you could sidestep the framework, and write your own Model functions if you wanted to. Use beforeSave() to manipulate your data in the model, then a myCustomSave() or similar. Then you can do $this->Model->myCustomSave() in your controller. There is always $this->Model->query($sql) for a custom insert, but fat models is more preferable than sql heavy controllers.
DavidYell
A: 

I'd recommend using the Polymorphic Behavior. I often do this for a Binary model 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. the id field in the photos table, for example).

Rob Wilkerson
Thanks! This is probably what I've been looking for.
Mef
It should do exactly what you want if I understand correctly. It's a brilliant behavior for managing multiple associations without duplicating data or structure.
Rob Wilkerson
A: 

For all of you looking for working solution using polymorphic behavior and MeioUpload, check out this. I'm using it right now and it seems to work fine.

Mef