Reputation: 999
I have three models Restaurant
Menu
Section
Restaurant contains id
name
Menu should only contain the restaurantId
and that record's id
Section contains id
name
menuId
How do I associate the models, such that, I would have a resultant table like this
Restaurant
Id Name
----- ---------
12 foo
24 bar
Menu
Id restaurantId
----- ------------
A 12
B 24
Section
Id menuId name
----- ------------ -------
S1 A Burgers
S2 A Sandwiches
S3 B Beverages
Upvotes: 2
Views: 1230
Reputation: 318
create table : resturant
create table restaurant(
r_id serial primary key,
r_name varchar(32)
)
create table : menu
create table menu(
r_id serial references restaurant(r_id),
m_id serial primary key
)
create table: sect
create table sect(
m_id serial references menu(m_id),
s_id serial primary key,
s_name varchar(32)
)
now denife Sect model :
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
}
})
}
same way define another 2 model of menu and resturant table then below query :
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)
})
}
now just call above method to enter data using association :
enterDataInRestaurant('foo',['Burger','Sandwich']);
enterDataInRestaurant('bar',['Beverages']);
Upvotes: 1