我有三个模型 Restaurant
Menu
Section
餐厅包含id
name
菜单应仅包含 restaurantId
和该记录的 id
部分包含 id
name
menuId
我如何关联模型,这样,我就会得到一个这样的结果表
餐厅
Id Name
----- ---------
12 foo
24 bar
菜单
Id restaurantId
----- ------------
A 12
B 24
部分
Id menuId name
----- ------------ -------
S1 A Burgers
S2 A Sandwiches
S3 B Beverages
最佳答案
创建表:餐厅
create table restaurant(
r_id serial primary key,
r_name varchar(32)
)
创建表:菜单
create table menu(
r_id serial references restaurant(r_id),
m_id serial primary key
)
创建表:sect
create table sect(
m_id serial references menu(m_id),
s_id serial primary key,
s_name varchar(32)
)
现在确定教派模型:
getSectModel(){
return sequelizeObj.define('sect',{
m_id:{
type: ORM.INTEGER,
foreignKey: true
},
s_id: {
type: ORM.INTEGER,
autoIncrement: true,
primaryKey: true
},
s_name: {
type: ORM.STRING
}
})
}
用同样的方法定义另外两个菜单和餐厅表模型,然后在下面查询:
enterDataInRestaurant(rname:string , sname:string[]){
var sect = this.getSectModel();
var menu = this.getMenuModel();
var resturant = this.getRestaurantModel();
// This below 2 line is for association
resturant.hasOne(menu, {foreignKey: 'r_id'})
menu.hasMany(sect, {foreignKey: 'm_id'})
resturant.create({
r_name: rname
menu:{
sects:[
{s_name: sname[0]},
{s_nmae: sname[1]}
]
}
},
{
include:[{
model: menu,
include:[{
model:sect
}]
}]
}).then(function(result){
console.log("results tag : "+result)
}).catch(function(error){
console.log("error",error)
})
}
现在只需调用上面的方法来使用关联输入数据:
enterDataInRestaurant('foo',['Burger','Sandwich']);
enterDataInRestaurant('bar',['Beverages']);
关于mysql - 如何在 sequelize 中关联和填充模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48137232/