laravel - 多个模型中的 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);
}
}
问题是如何建立
Product
与ProductImage
模型之间的关系?如何设计
product_images
餐桌?
id
, color_id
,image
像这样?
我的用例是,我将在单个产品页面上制作一个滑块。将有一个颜色选择选项。如果用户选择一种颜色,则需要加载与该选择的颜色相关联的产品图像。
感谢你的帮助 :)
解决方案
我也在做一个电子商务项目,我设计了我的数据库,如下所示。
一个产品有多个产品颜色,但一个产品颜色只属于一个产品。产品 id 和颜色一起成为 product_colors 表的复合键(唯一)。
如果您有一件 id 为 101 且产品颜色为红色的产品 T 恤,那么 101 和红色一起是唯一的 product_color。
Product_image 属于 product 和 product_colors 表。product_id 和 product_color_id 一起是复合键。如果您有多个相同产品 ID 和颜色的图像,则可以将图像保存为 JSON 数据。我为我的应用程序所做的。
推荐阅读
- javascript - React Hooks:在“本地状态”中清除/设置超时是否像这样不好?
- php - 将 3 列的数据库结果转换为关联数组
- javascript - 如何让用户删除使用“画线”按钮创建的线
- python - 从 qtreeview 获取当前选定的数据,而不是以前的
- perl - perl 多行搜索和替换
- nginx - Certbot 安装无法在 nginx 上运行
- c++ - c++,成员线程对象在运行时导致结构删除崩溃
- angular - 将 ActivatedRoute 可观察对象与 API 请求中的可观察对象结合起来
- c# - 如何从实体编号表示中获取 HTML 实体名称
- python - 如何使用重复键在 Pandas 中旋转此数据框?