首页 文章

如何在没有圆圈的情况下建模多对多关系

提问于
浏览
1

Note: Because my original question wasn't understood clearly I'm writing it completely new!
我的数据库中有两个表,还有一个联结/连接表:
Recipes:

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

Ingredients:

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

IngredientsRecipes:

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

My Ingredient class in php code looks like this:

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

And this is my Recipes class:

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

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

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

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

1 回答

  • 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)
    );
    

相关问题