node.js - 在 Node JS 和 Sequelize 中查询 N:M 关联的连接表
问题描述
对于拥有资产的用户,我有一个经典的多对多关系:资产可以在其生命周期内转移给其他用户,因此在 AssetUser“通过表”中记录了一个窗口时间,并添加了 STARTDATE 和 ENDDATE 属性。
用户表
const User = sequelize.define('User', {
ID: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true
},
FIRSTNAME: {
type: DataTypes.STRING,
allowNull: false
},
LASTNAME: {
type: DataTypes.STRING,
allowNull: false
}},{ timestamps: false }});
资产表
const Asset = sequelize.define('Asset', {
ID: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true
},
DESCRIPTION: {
type: DataTypes.STRING,
allowNull: false
}},{ timestamps: false }});
AssetUser 连接表
const AssetUser = sequelize.define('AssetUser', {
id: {
type: DataTypes.INTEGER.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
UserID: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: User,
key: 'ID'
}
},
AssetID: {
type: DataTypes.INTEGER.UNSIGNED,
references: {
model: Asset,
key: 'ID'
}
},
STARTDATE: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
ENDDATE: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: null
}},{ timestamps: false });
模型在这里创建:
User.belongsToMany(Asset, { through: { model: AssetUser, unique: false }, uniqueKey: 'id' });
Asset.belongsToMany(User, { through: { model: AssetUser, unique: false }, uniqueKey: 'id' });
我的问题是我想查询并查找在限制期间内由一个用户拥有的一项资产的所有结果。我无法查询连接表,只能查询用户和资产表。如何在查询中为 AssetUser 表添加“位置”条件?我应该如何在下面插入 STARTDATE 和/或 ENDDATE 条件?
Asset.findAll({
where: {
DESCRIPTION: 'Personal computer'
},
include: {
model: User,
where: {
FIRSTNAME: 'Marcello'
}
}});
谢谢你的帮助。
解决方案
我找到了解决方案
Asset.findAll({ where: { DESCRIPTION: 'Personal computer' }, include: { model: User, through: { where: { FIRSTNAME: 'Marcello' } } }});
推荐阅读
- sequelize.js - Sequelize 别名关联上的急切加载错误
- flutter - 水平和垂直扩展/收缩一个容器,而其他容器在 Flutter 中保持固定
- react-native - 超过 12 的 iOS 模拟器超过了最大调用堆栈大小
- javascript - 如何在节点js的mongodb中获取预先选择的选项
- c# - 是否可以有一个 MySQL 查询并根据是否存在行选择 INSERT 或 UPDATE?
- azure - 从 LAN 创建类似云的 Azure?
- mysql - 如何将SQL表中的一列从短文本修改为长文本
- java - 用于查找最高元素的并行数组
- selenium - 使用 selenium 执行脚本时出错
- arrays - 在 Swift 中,如何检查数组的第一个元素是否等于值列表?