首页 > 解决方案 > 在 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'
    }
}});

谢谢你的帮助。

标签: node.jssequelize.js

解决方案


我找到了解决方案

Asset.findAll({ where: {     DESCRIPTION: 'Personal computer' }, include: {     model: User, through: {     where: {         FIRSTNAME: 'Marcello'     } } }});

推荐阅读