【问题标题】:Query in join-table for N:M associations in Node JS and Sequelize在连接表中查询 Node JS 和 Sequelize 中的 N:M 关联
【发布时间】:2021-06-22 10:42:32
【问题描述】:

对于拥有资产的用户,我有一个经典的多对多关系:资产可以在其生命周期内转移给其他用户,因此在 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.js sequelize.js


    【解决方案1】:

    我找到了解决办法

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      相关资源
      最近更新 更多