【问题标题】:How to model many to many relationships without circles如何在没有圆圈的情况下建模多对多关系
【发布时间】:2023-03-08 01:17:01
【问题描述】:

注意:因为我最初的问题没有被清楚地理解,所以我写的是全新的!
我的数据库中有两个表,还有一个联结/连接表:
食谱:

CREATE TABLE Recipes(
    id INT(11) NOT NULL AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    PRIMARY KEY (id)
)

成分:

CREATE TABLE Ingredients(
    id INT(11) NOT NULL AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    PRIMARY KEY (id)
)

成分食谱:

CREATE TABLE IngredientsRecipes(
    id INT(11) NOT NULL AUTO_INCREMENT,
    recipeId INT(11) NOT NULL,
    ingredientId INT(11) NOT NULL,
    PRIMARY KEY (id)
)

我的 php 代码中的成分类如下所示:

class Ingredient{
        private $id;
        private $name;
        private $recipes; //In which recipes this ingredient is used
}

这是我的食谱课:

class Recipe{
        private $id;
        private $name;
        private $ingredients; //Ingredients used in this Recipe
}

现在,当我想填充两个列表时,我遇到了以下问题: Recipe 类有很多成分,成分类有很多食谱。每个类都包含其他类,我希望这张小图可以说明情况。

Recipe          | Ingredients   | Recipes using   |
                |used in Recipe | this Ingredient |
----------------+---------------+-----------------+

                |--Noodles------|Spaghetti
                |
Spaghetti-------|--Sauce--------|--Spaghetti   
                |
                |--Cheese-------|--Spaghetti
                                |
                                |--Mac n Cheese

                |--Macaroni-----|Mac n Cheese
                |
Mac n Cheese----|--Cheese-------|--Spaghetti
                                |            
                                |--Mac n Cheese

为多对多关系编写模型类的首选方式是什么?

【问题讨论】:

  • 米奇说了什么。这通常称为“连接表”。但是,我将其命名为 RecipesIngredients 以明确其用途。
  • 我知道连接表的概念,但这只是数据库站点,我想知道如何在我的代码中表示该关系
  • 或者我应该创建一个RecipeIngredient 类,然后创建一个recipeIngredient 对象列表?
  • 或许您可以告诉我们您使用的是什么编程语言或 ORM?
  • 我使用的 PHP 没有任何 orm 或框架

标签: database relationship geometry


【解决方案1】:

这通常通过连接或映射表来完成,以保存两者之间的关系,例如:

CREATE TABLE recipe (
    recipe_id NUMERIC PRIMARY KEY
    recipe_name VARCHAR (100)
    -- etc...
);

CREATE TABLE ingredient (
    ingredient_id NUMERIC PRIMARY KEY
    ingredient_name VARCHAR (10),
    -- etc...
);

CREATE TABLE recipe_ingredient (
    recipe_id NUMERIC REFERENCES recipe (recipe_id),
    ingredient_id NUMERIC REFERENCES ingredient (ingredient_id),
    PRIMARY KEY (recipe_id, ingredient_id)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多