【问题标题】:Create a product's property table dependent on type根据类型创建产品的属性表
【发布时间】:2016-04-01 01:44:31
【问题描述】:

我在 Laravel 5 上创建应用程序时遇到了问题。 我正在尝试创建产品的属性,这些属性取决于属性类型(整数、字符串、布尔值)。

有一个“产品”表:

  • id - int、pk、ai、uns
  • 名称 - 字符串
  • 代码 - 字符串
  • 价格 - 浮动 null

'属性'表:

  • id - int、pk、ai、uns
  • 名称 - 字符串
  • 代码 - 字符串

产品型号代码:

class Product extends Model
{
    public function properties()
    {
        return $this->belongsToMany(Property::class);
    }
}

物业型号代码:

class Property extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class);
    }
    public function integers()
    {
        return $this->morphedByMany(PropertyInteger::class, 'property_type', 'product_property');
    }
    public function strings()
    {
        return $this->morphedByMany(PropertyString::class, 'property_type', 'product_property');
    }
}

PropertyInteger 代码(ProductString 代码相同):

class PropertyInteger extends Model
{
    public function properties()
    {
        return $this->morphToMany(Property::class, 'property_type', 'product_property');
    }
}

然后我尝试获取产品的所有属性及其值: (new App\Product)->with(['properties', 'properties.integers', 'properties.strings']); 我得到的所有属性都不是属于 Product 模型的,但是在值中我得到了所有属性的所有值。

谢谢。

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    您的关系数据模型应修改为:

    Produts:
    id - int, pk, ai, uns
    name - string
    code - string
    price - float null
    
    Properties:
    id - int, fk(Products(id)), uns
    pnum - short, ai(by id), uns
    name - string
    code - string
    - pk(id, pnum)
    

    我编写了描述以下关系的语法:Properties 应该有一个复合主键 (id, pnum) 其中idProducts 的外键(通过id)。如果给定产品的每种类型只允许一个属性,那么pnum 可以是一个表示类型的小整数(为了清楚起见,您甚至可能需要一个单独的定义表。

    要获得将属性与产品匹配的结果集,您可以执行内部联接(如果您想省略没有属性的产品)或将产品作为左侧表的左外部联接。无论哪种情况,连接谓词都是Products.id = Properties.id

    尔格-

    select
        ...
    from
        Products
            inner join   <-- or left outer join if wanting to include propertyless products
        Properties
            on (Products.id = Properties.id)
    where
        ...
    

    【讨论】:

    • 1 产品可以有许多属性,这不是问题并且有效。但是产品可以有许多值,其中一些是整数,其中一些是字符串和布尔值。问题在于不同的数据类型。如果我有 1 种数据类型“hasManyThrough”关系可以解决我的问题。但是有3种数据类型
    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 2018-09-08
    相关资源
    最近更新 更多