开发者

One table for uploads for multiple resources in CakePHP

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 ima开发者_如何学Goge is coming from which resource?


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜