如何在sequelize中关联和填充模型?

时间:2018-01-07 12:46:21

标签: mysql node.js sequelize.js

我有三个模型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

1 个答案:

答案 0 :(得分:1)

创建表:resturant

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

现在否定Sect模型:

  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
        }
    })
  }

以同样的方式定义菜单和resturant表的另一个模型然后在查询下面:

  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']);