简体   繁体   English

Sequelize MySQL - 连接同一个关联表中的两行

[英]Sequelize MySQL - Join with two rows from same associated table

I am into a tricky question involving Sequelize MySQL.我遇到了一个涉及 Sequelize MySQL 的棘手问题。 I have two models: Calibration and Device , associated many-to-one respectively.我有两个模型: CalibrationDevice ,分别关联多对一。

const Calibration = sequelize.define('Calibration', {
        id: {
            type: DataTypes.UUID,
            primaryKey: true,
            defaultValue: DataTypes.UUIDV4
        },
        date: {
            type: DataTypes.DATEONLY,
            allowNull: false
        },
        document: DataTypes.STRING,
        status: DataTypes.STRING
    });

    Calibration.associate = (models) => {
        models.Calibration.belongsTo(models.Device, {
            foreignKey: 'deviceId',
            onDelete: 'CASCADE'
        });
    };


const Device = sequelize.define('Device', {
        id: {
            type: DataTypes.STRING,
            primaryKey: true,
            defaultValue: DataTypes.UUIDV4
        },
        name: DataTypes.STRING,
        description: DataTypes.STRING,
        serialNo: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true
        },
        calibrationPeriod: DataTypes.INTEGER,
        location: DataTypes.STRING,
        seller: DataTypes.STRING,
        servicePartner: DataTypes.STRING,
        deviceFunction: DataTypes.STRING,
        quantity: DataTypes.INTEGER,
        status: DataTypes.STRING,
        comment: DataTypes.STRING
    });

Now the point is that I want to query a list of Device , joined with Calibration , each device item has two date attributes referencing two associated calibrations, one with most recent date and the other with the nearest date in future.现在的重点是我想查询一个Device列表,加入Calibration ,每个设备项都有两个日期属性,引用两个关联的校准,一个是最近的日期,另一个是未来最近的日期。 It has been quite tricky and I haven't managed to find out solution.这非常棘手,我还没有设法找到解决方案。 Thank you very much for your help.非常感谢您的帮助。

Updated: This is my current doing, in fact, I'm not satisfied with this yet, as I prefer another way of combining it all in 1 query only, instead of 3 like this:更新:这是我目前正在做的,事实上,我对此并不满意,因为我更喜欢另一种方式将它全部组合在 1 个查询中,而不是像这样的 3 个:

let result = await Device.findAll({
                    include: [{ model: Category, attributes: ['id', 'name'] }],
                    order: [['createdAt', 'DESC']], raw: true
                });
await Promise.map(result, async (item, i) => {
    const lastCalibration = await Calibration.findAll({
                        attributes: ['id', 'date'],
                        where: { date: { [Op.lte]: Sequelize.fn('curdate') }, deviceId: item.id },
                        include: [{ model: Device, attributes: ['id'] }],
                        order: [['date', 'DESC']],
                        limit: 1,
                        raw: true
                    });
    const nextCalibration = await Calibration.findAll({
                        attributes: ['id', 'date'],
                        where: { date: { [Op.gt]: Sequelize.fn('curdate') }, deviceId: item.id },
                        include: [{ model: Device, attributes: ['id'] }],
                        order: [['date', 'ASC']],
                        limit: 1,
                        raw: true
                    });
result[i] = { ...item, lastCalibration: lastCalibration[0], nextCalibration: nextCalibration[0] };

I think the associations can be achieved through:我认为可以通过以下方式实现关联:

include: [Calibration], 
through: { 
    where: {
      [Op.or]: [
      { date1: '10-12-2020' },
      { date2: '11-12-2020' }
    ]
   }
 },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM