Laravel relations in multiple model with belongsToMany and hasMany

Viewed 743

I am working on an eCommerce application.

I have 3 models. Product, Color, ProductImage.

The relation between Product and Color is: belongsToMany

<?php

namespace App\Entities\Product;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * A product has many colors.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function colors()
    {
        return $this->belongsToMany(Color::class);
    }
}

The relation between Color and ProductImage is: hasMany

<?php

namespace App\Entities\Product;

use Illuminate\Database\Eloquent\Model;

class Color extends Model
{
    /**
     * A color has many images.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function images()
    {
        return $this->hasMany(ProductImage::class);
    }
}

Question is how to make a relation between the Product and ProductImage model?

How to design the product_images table?

id, color_id, image

like this?

my use case is, I will make a slider on a single product page. There will be a Color select option. If a user selects a color, need to load product images associate with that selected color.

Appreciate your help :)

2 Answers

I am also working on an e-commerce project and I have designed my database like below.

A product has multiple product colors but a product color belongs to only one product. product id and color together a compound key(unique) of the product_colors table.

If you have a product T-shirt which id is 101 which product color is red then together 101 and red are a unique product_color.

Product_image belongs to the product and product_colors table. Together product_id and product_color_id are composite key. In case if you have multiple images for the same product id and color then you can save the image as JSON data. which I did for my application.

enter image description here

Although I have designed my database like fig 01. But if we want to separate the colors table then we could design the database like this. enter image description here

If you need only productImages, you can use belongsToManyThrough. But if you need colors and productImages you can do it through the dot.

$product->load('colors.images');

UPD Read your description, in my point of view, table images should have two keys product_id and color_id. And then do something like this:

public function images()
{
    return $this->hasMany(ProductImage::class);
}

public function current_image(int $color_id)
{
    return $this->hasOne(ProductImage::class)->where('color_id', $color_id);
}
Related