简体   繁体   中英

Laravel 5.1 - Polymorphic relationship for multiple columns

I have the next tables:

images (id, filename ...)

pages (title, slug ...)

users (username, email ...)

I created an imageables table to keep image relations

image_id / imageable_id / type (Pages / Users etc.)

It works fine if I only need a single image(s) field per model.

But how should I proceed if I need for example header_image and paragraph_image in one page ?

If I want a single header_image / paragraph_image I can keep the field directly in the model (header_image_id, paragraph_image_id) but what if I have a top slider and a gallery for the article.. I will need 2 manyToMany relations.

Is it possible to keep all of them in the same imageables table ? Theoretically I will need another column for unicity (a field name for example.)

I think you are not creating your tables and relationships properly. In your case I would create 2 different tables: pages and images with a pivot table relationship.

  1. Pages table: id, title, slug...
  2. Images table: id, type , filename...
  3. Pivot table (Images and Pages): page_id, image_id.

Then you can simple use the type column of the Images table to set the place where you want to put that image. You can set type equals to header or paragraph or slider...

$image = new Image;
$image->type= 'header';
$image->filename = 'yourimage.jpg';
...
$image->save();

In your view you can retrieve the image you want for your header, paragraph, slider like this:

$page->images()->where('type', 'header')->first();

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM