Question

I am having a peculiar problem when using association in Sequelize.

I have two models

Rock

rock_id         : { type: DataTypes.BIGINT, allowNull: false, primaryKey: true, autoIncrement: true },
rock_mode_id    : { type: DataTypes.BIGINT },

with associations:

associate: function(models) {
                    rock.hasOne(models.rock_mode, {foreignKey: "rock_mode_id"})
}

Rock Mode

rock_mode_id    : { type: DataTypes.BIGINT, allowNull: false, primaryKey: true },
rock_mode       : { type: DataTypes.STRING }

with assocations:

associate: function(models) {             
    rock_mode.belongsTo(models.rock, {foreignKey: "rock_mode_id", foreignKeyConstraint:false })
}

I am attempting to print out Rock with the RockMode but it is seeming to point to the wrong id

Here is the code for the render (in rockString):

db.rock
    .findAll({include: [db.rock_mode]})
    .success(
        function(rocks) {
            rockString += "<h2>Rocks</h2>"
            rocks.forEach(function(rock) {
                rock.getRockModeName(function(rockModeName){
                    rockString += JSON.stringify(rock)
                    callback(rockString);
                })

            })

    })

When I see the output:

{"rock_id":1,"rock_mode_id":1,"rock_mode":{"rock_mode_id":1,"rock_mode":"a"}}
{"rock_id":2,"rock_mode_id":1,"rock_mode":{"rock_mode_id":2,"rock_mode":"b"}}
{"rock_id":3,"rock_mode_id":1,"rock_mode":null}
{"rock_id":4,"rock_mode_id":1,"rock_mode":null}
{"rock_id":11,"rock_mode_id":1,"rock_mode":null}

It seems as if the the "rock_mode_id" of the "rock_mode" is referencing the "rock_id" instead of the "rock_mode_id". Does anyone know why? Is there an issue with my hasOne or belongsTo? Or should I specify a where into the include?

EDIT: EDIT: it IS pointing to the wrong id, here is the resulting SQL

Executing (default): SELECT `rocks`.*, `rock_mode`.`rock_mode_id` AS `rock_mode.rock_mode_id`, `rock_mode`.`rock_mode` AS `rock_mode.rock_mode` FROM `rocks` LEFT OUTER JOIN `rock_modes` AS `rock_mode` ON `rocks`.`rock_id` = `rock_mode`.`rock_mode_id`;

Here's the problem:

LEFT OUTER JOIN `rock_modes` AS `rock_mode` ON `rocks`.`rock_id`=`rock_mode`.`rock_mode_id`;

This should say

 ON `rocks`.`rock_mode_id`=`rock_mode`.`rock_mode_id`;
Was it helpful?

Solution

As answered on GitHub you need to invert your association. For your schema Rock belongsTo RockMode, it does not have one, since the foreignKey is on Rock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top