JS Sequelize "Where Related" Query?

JS Sequelize "Where Related" Query?

本文关键字:quot Query Related Where JS Sequelize      更新时间:2023-09-26

我不知道如何执行特定类型的查询。

不确定Sequelize社区会怎么称呼它,但Codeigniter PHP框架将其称为"where_related"查询。

例如,假设我有两种对象类型:hotelRoom和roomStyle。

hotelRoom具有属性roomNumber和相关的roomStyle对象。

假设我想查找与具有roomNumber<200

Sequelize能在不使用原始SQL的情况下做到这一点吗?

查看文档中的急切加载和一对多关联。

var HotelRoom = sequelize.define('HotelRoom', { roomNumber: DataType.INTEGER })
,   RoomStyle  = sequelize.define('RoomStyle');
// this will add the HotelRoomId column to RoomStyle table
HotelRoom.hasMany(RoomStyle);
// create an instance of room and make it the parent of a style
HotelRoom.create({ roomNumber: 5 })
.then(function(room){
  return RoomStyle.create()
  .then(function(style){
    room.addStyle(style)
  })
})

然后,您可以使用热切加载方法返回一系列房间编号的所有房间样式。

RoomStyle.findAll({ 
  include: [{ 
    model: HotelRoom, 
    attributes: [], 
    where: { roomNumber: { lt: 200 } } // i.e. "less than 200"
  }] 
})
.then(function(res){ 
  console.log(res) 
});

所有这些都假设房间和样式之间的关系是一对多的。要定义多对多关系,只需定义返回到另一个方向的关系(以上代码仍然有效)。

// define a many-to-many relationship through the junction table "RoomsStyles"
HotelRoom.hasMany(RoomStyle, { through: RoomsStyles });
RoomStyle.hasMany(HotelRoom, { through: RoomsStyles });

干杯,希望这有帮助。