首页 > 解决方案 > 多个模型中的 Laravel 关系与 belongsToMany 和 hasMany

问题描述

我正在开发一个电子商务应用程序。

我有 3 个模型。Product, Color, ProductImage.

Product和之间的关系Color是: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);
    }
}

Color和之间的关系ProductImage是: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);
    }
}

问题是如何建立ProductProductImage模型之间的关系?

如何设计product_images餐桌?

id, color_id,image

像这样?

我的用例是,我将在单个产品页面上制作一个滑块。将有一个颜色选择选项。如果用户选择一种颜色,则需要加载与该选择的颜色相关联的产品图像。

感谢你的帮助 :)

标签: laraveleloquent

解决方案


我也在做一个电子商务项目,我设计了我的数据库,如下所示。

一个产品有多个产品颜色,但一个产品颜色只属于一个产品。产品 id 和颜色一起成为 product_colors 表的复合键(唯一)。

如果您有一件 id 为 101 且产品颜色为红色的产品 T 恤,那么 101 和红色一起是唯一的 product_color。

Product_image 属于 product 和 product_colors 表。product_id 和 product_color_id 一起是复合键。如果您有多个相同产品 ID 和颜色的图像,则可以将图像保存为 JSON 数据。我为我的应用程序所做的。

在此处输入图像描述

虽然我已经设计了我的数据库,如图 01。但是如果我们想分离颜色表,那么我们可以这样设计数据库。 在此处输入图像描述


推荐阅读