我在查询中添加包含时遇到问题,我不知道为什么。我有两种模型:用户和交易
用户
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('User', {
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
email: DataTypes.STRING
}, {});
User.associate = function(models) {
User.hasMany(models.Transaction, {
foreignKey: 'senderId',
as: 'sender',
}),
User.hasMany(models.Transaction, {
foreignKey: 'receiverId',
as: 'receiver',
})
};
return User;
};
交易
module.exports = (sequelize, DataTypes) => {
var Transaction = sequelize.define('Transaction', {
amount: DataTypes.INTEGER
}, {});
Transaction.associate = function(models) {
Transaction.belongsTo(models.User, {
foreignKey: 'senderId'
}),
Transaction.belongsTo(models.User, {
foreignKey: 'receiverId'
})
};
return Transaction;
};
迁移后,db中可以同时使用senderId和receiverId。
尝试查询:
Transaction
.findAll({
where: { senderId: req.params.userId },
include: [{
model: User,
as: 'sender',
},{
model: User,
as: 'receiver',
}],
})
预期结果:
{
"transactions": [
{
"id": 2,
"amount": 300,
"sender": {
"id": 2,
"firstName": "John",
"lastName": "Doe",
"email": "jdoe+123@gmail.com",
},
"receiver": {
"id": 3,
"firstName": "John1",
"lastName": "Doe1",
"email": "jdoe+132@gmail.com",
}
},
{
"id": 3,
"amount": 900,
"sender": {
"id": 2,
"firstName": "John",
"lastName": "Doe",
"email": "jdoe+123@gmail.com",
},
"receiver": {
"id": 3,
"firstName": "John1",
"lastName": "Doe1",
"email": "jdoe+132@gmail.com",
}
}
]
}
但是我遇到了错误: SequelizeEagerLoadingError
他们的关联或查询有问题吗?
答案 0 :(得分:1)
您需要为这些关联中的一个或两个添加别名,当前它们正在相互覆盖。 像这样:
module.exports = (sequelize, DataTypes) => {
var Transaction = sequelize.define('Transaction', {
amount: DataTypes.INTEGER
}, {});
Transaction.associate = function(models) {
Transaction.belongsTo(models.User, {
as: 'sender',
foreignKey: 'senderId'
}),
Transaction.belongsTo(models.User, {
as: 'receiver',
foreignKey: 'receiverId'
})
};
return Transaction;
};