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

ou6hu8tu  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(327)

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

fjnneemd1#

创建表: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)
)

现在是丹尼派模特:

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

同样的方法定义菜单和餐厅表的另外2个模型,然后在下面查询:

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

相关问题