【问题标题】:One or multiple models/tables for relation that can exist on multiple models可以存在于多个模型上的关系的一个或多个模型/表
【发布时间】:2020-05-26 19:55:19
【问题描述】:

我有一个模型“Wine”和一个模型“Drink”。 Wine 和 Drink 都应该有一个类型 (type_id)。

所以数据库应该看起来像这样:

葡萄酒

id, name, type_id, etc.

id, name, type_id, etc.

我的问题是:

我应该

  1. 制作模型“DrinkType”和模型“WineType”或
  2. 我应该只使用一种,称为“类型”吗?

酒类

id, name

饮料类型

id, name

类型

id, name, type


nr 的 DB 示例。 1:

葡萄酒

  • id、名字、wine_type_id
  • 1、试酒1、1
  • 2、试酒2、2

饮料

  • id、姓名、drink_type_id
  • 1,试饮,1

葡萄酒类型

  • 身份证、姓名
  • 1,红色
  • 2,白

饮料类型

  • 身份证、姓名
  • 1、鸡尾酒

nr 的 DB 示例。 2:

葡萄酒

  • id、name、type_id
  • 1、试酒1、1
  • 2、试酒2、3

饮料

  • id、name、type_id
  • 1、试饮、2

类型

  • id、名称、类型
  • 1,红色,App\Wine
  • 2,鸡尾酒,App\Drink
  • 3,白,App\Wine

我正在使用框架“Laravel”并且我知道多态关系。但这是正确的方法吗? https://laravel.com/docs/7.x/eloquent-relationships#one-to-many-polymorphic-relations

我希望我的问题是有道理的,并且有人有一些提示可以解决我的问题:)

【问题讨论】:

    标签: php mysql database laravel polymorphism


    【解决方案1】:

    为此,您需要遵循一对一(多态)关系。

    葡萄酒 型号名称:- 葡萄酒

    id 
    name
    

    饮料型号名称:- 饮料

    id, 
    name,
    

    类型

    id - integer
    body - text
    typeable_id - integer
    typeable_type - string
    

    您正在关注正确的一个。 https://laravel.com/docs/7.x/eloquent-relationships#one-to-one-polymorphic-relations

    【讨论】:

    • 但是如果我有两种相同类型的葡萄酒怎么办?类型 id, name, typeable_id, typeable_type 1, Red, 1, App\Wine 2, Red, 2, App\Wine Wine 1 和 2 应该具有相同的类型“Red”。但是通过这种方式,它将生成两种类型,都名为“Red”。我怎样才能使它们具有相同的类型?
    • 好的,cmets 删除所有格式。所以我希望我的最后评论是有道理的。
    • 哦,是的,它应该是一对一(多态),所以下次如果 RED 出现在 Wine 上,它会更新。检查这个laravel.com/docs/7.x/…
    • 我不明白它怎么可以是一对一的。 1 酒只能有 1 种类型。但是 1 Type 可以属于多个 Wine。所以它应该是一对多,不是吗?但这就像它应该是一对多倒置的。但是倒数如何处理多态性呢?
    【解决方案2】:

    我决定选择后者。

    数据库如下所示:

    葡萄酒

    id, name, type_id
    

    id, name, type_id
    

    类型

    id, name, model
    

    例子:

    葡萄酒

    1, 2013 Gran Selezione, 1
    2, 2013 Barolo Bussia, 1
    3, 2018 Juwel Riesling, 4
    

    1, Blueberry Mojito, 2
    2, Chili-infused honey, 3
    

    类型

    1, Red, App\Wine
    2, Cocktail, App\Drink
    3, Garnish/Mixer, App\Drink
    4, White, App\Wine
    

    然后在我的 WineController 和 DrinkController 中,我将像这样验证 type_id:

    • 葡萄酒: 'type_id' => 'required|integer|exists:types,id,model,"App\Wine"'

    • 饮料: 'type_id' => 'required|integer|exists:types,id,model,"App\Drink"'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多