我不确定如何执行特定类型的查询。
不确定 Sequelize 社区会如何调用它,但 Codeigniter PHP 框架将其称为“where_lated”查询。
例如,假设我有 2 种对象类型:hotelRoom 和 roomStyle。
hotelRoom 具有属性 roomNumber 和相关的 roomStyle 对象。
假设我想查找与 roomNumber < 200 的 hotelRoom 对象相关的所有 roomStyle 对象
Sequelize 可以在不诉诸原始 SQL 的情况下完成此操作吗?
最佳答案
查看 eager loading 的文档和 one-to-many协会。
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 });
干杯,希望这对您有帮助。
关于javascript - JS Sequelize "Where Related"查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20600547/