注意:因为我原来的问题没有被清楚地理解,所以我将它写成全新的!
我的数据库中有两个表,加上一个结点/连接表:
食谱:
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)
)
IngredientsRecipes:
CREATE TABLE IngredientsRecipes(
id INT(11) NOT NULL AUTO_INCREMENT,
recipeId INT(11) NOT NULL,
ingredientId INT(11) NOT NULL,
PRIMARY KEY (id)
)
php代码中的我的Ingredient类看起来像这样:
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 | 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
为多对多关系编写模型类的首选方法是什么?
答案 0 :(得分: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)
);