简体   繁体   中英

creating association with multiple foreign keys using sequelize.js

I am looking to use sequelize.js to make one call and ping two tables.

I want my results to find the corresponding data within my second table that match with two foreign keys - 'timeperiod' and 'nodeid'

Currently, regardless of different alias(s) - my query results in only matching the last foreign key I specify. Hence time period in this case.

associate: function (models) {
    models.belowOcfBudget.belongsTo(models.belowOcf, {
        foreignKey: 'nodeid',
        targetKey: 'nodeid',
        as: 'belowOcf_id'
    });
    models.belowOcfBudget.belongsTo(models.belowOcf, {
        foreignKey: 'timeperiod',
        targetKey: 'timeperiod',
        as: 'belowOcf_time'
    });
}

Below is where i include this association in my router.

    BelowOCFBudget.findAll({
    raw: true,
    include:[{
        model: models.belowOcf,
        as: 'belowOcf_id'
    }],
    include:[{
        model: models.belowOcf,
        as: 'belowOcf_time'
    }]

how can I have my query execute and return me a data set from two tables that have matching timeperiod and id?

You shouldn't include your associated model twice. That results in to LEFT JOIN on the same table, one for every foreign key. Instead include it just once and add the matching of your second foreign key as additional where clause to the include.

Haven't tested it, but that should look something like this:

BelowOCFBudget.findAll({
    raw: true,
    include:[{
        model: models.belowOcf,
        where: {belowOcf.timeperiod: timeperiod}
    }],
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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