PROBLEM
I'm using sequelize to make an auto-generated query with a JOIN and I get that :
SELECT [...] FROM `weapon` AS `weapon` LEFT OUTER JOIN `stat` AS `mainStat` ON `weapon`.`ID` = `mainStat`.`ID` WHERE `weapon`.`type` = 'polearm';
However, the ON clause is incorrect, in fact, I want that :
[...] ON `weapon`.`mainStatID` = `mainStat`.`ID` [...]
Here is the associations I declared :
Weapon.hasOne( Stat, { foreignKey: 'mainStatID', as: 'mainStat' });
Stat.belongsTo( Weapon );
Stat.belongsTo( Weapon );
Just don't change anything.
Maybe I didn't understand something with .hasOne()
and .belongsTo()
concept ?
MODELS
Here is the two concerned Models :
const Weapon = sequelize.define('weapon', {
ID : { type: DataTypes.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true },
name : { type: DataTypes.STRING, allowNull: false },
shortName : { type: DataTypes.STRING, allowNull: false },
type : { type: DataTypes.STRING, allowNull: false },
rarity : { type: DataTypes.INTEGER, allowNull: false },
baseAtk : { type: DataTypes.INTEGER, allowNull: false },
mainStatID : { type: DataTypes.INTEGER, allowNull: false },
description : { type: DataTypes.STRING, allowNull: false },
maxStack : { type: DataTypes.BOOLEAN, allowNull: false },
optionalEffect: { type: DataTypes.STRING, allowNull: true }
},
{
freezeTableName: true,
timestamps: false
})
const Stat = sequelize.define('stat', {
ID : { type: DataTypes.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true },
displayName: { type: DataTypes.STRING, allowNull: false },
shortName : { type: DataTypes.STRING, allowNull: false },
value : { type: DataTypes.FLOAT, allowNull: false, get() {return parseFloat(this.getDataValue('value'))} }
},
{
freezeTableName: true,
timestamps: false
})
*Using mysql and sequelize 6.25.4
CodePudding user response:
First of all, you should remove the explicit field definition for the foreign key:
mainStatID: { type: DataTypes.INTEGER, allowNull: false },
Secondly, if you would like a foreign-key field of MainStatID in the Weapon table then the relationship should be:
Weapon.belongsTo(Stat, { as: 'MainStat' });