How to paste value from query in query?
I want to get user data including his pair (association). To separate two associations from one table to another table I use "as". Please help me.
I tried to use the class name and sequelize.col, but apparently I am doing something wrong
Error
UnhandledPromiseRejectionWarning: SequelizeEagerLoadingError: Pairs is associated to Users multiple times. To identify the correct association, you must use the 'as' keyword to specify the ali
as of the association you want to include.
Query
const user = await userModel.findOne({ where: { id:userId }, attributes: ['id', 'login', 'sex'], include: { model: pairModel, as: userModel.sex } });
User Model
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
User.hasOne(models.pair, {
as: 'male',
foreignKey: 'maleId',
});
User.hasOne(models.pair, {
as: 'female',
foreignKey: 'femaleId',
});
/*User.hasMany(models.Pair, {
foreignKey: 'firstId',
foreignKey: 'secondId',
});*/
}
};
User.init({
login: DataTypes.STRING,
password: DataTypes.STRING,
sex: { type: DataTypes.STRING, defaultValue: "male" },
}, {
sequelize,
modelName: 'Users',
});
return User;
};
Pair model
'use strict';
const {
Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class Pair extends Model {
/**
* Helper method for defining associations.
* This method is not a part of Sequelize lifecycle.
* The `models/index` file will call this method automatically.
*/
static associate(models) {
// define association here
Pair.belongsTo(models.user, {
as: 'male',
foreignKey: 'maleId'
});
Pair.belongsTo(models.user, {
as: 'female',
foreignKey: 'femaleId'
});
}
};
Pair.init({
homeWork: DataTypes.STRING,
}, {
sequelize,
modelName: 'Pairs',
},);
return Pair;
};