我有以下型号:
地址,用户和邀请。
他们之间的关系是这样的:
User.belongsTo(address)
Invitation.belongsTo(user, { as: 'userRequest', foreignKey: 'userRequestId'});
Invitation.belongsTo(user, { as: 'userInvited', foreignKey: 'userInvitedId'});
我想进行以下查询:
var filterAddress = {model: address,
attributes: [...]
}
invitation.findAll({
include: [
{
model: user,
as: 'userRequest',
include: [
filterAddress,
]
},
{
model: user,
as: 'userInvited',
include: [
filterAddress,
]
},
],
})
但是它返回了Not unique table / alias:'userInvited-> address。
我该如何解决?我还搜索了包含User for Addres模型中的别名,但仍无效。
答案 0 :(得分:0)
尝试这两种关系 -
Invitation.belongsTo(User, {
foreignKey : {
name : "userRequestId"
},
as : 'UserRequest'
});
答案 1 :(得分:0)
user.js的
module.exports = (sequelize, DataTypes) => {
var User= sequelize.define('user', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
.........
},{
timestamps: false,
freezeTableName: true,
});
User.associate = function(models) {
User.belongsTo(models.address);
.......
};
return User;
};
Invitation.js
module.exports = (sequelize, DataTypes) => {
var Invitation = sequelize.define('invitation', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
status: {
type: DataTypes.ENUM('Waiting', 'Accept','Cancel') ,
notNull: true
},
userRequestId: {
type: DataTypes.INTEGER,
references: {
model: 'user',
key: 'id'
},
` },
userInvitedId: {
type: DataTypes.INTEGER,
references: {
model: 'user',
key: 'id'
},
}
},{
timestamps: false,
freezeTableName: true,
});
Invitation.associate = function(models) {
Invitation.belongsTo(models.user, { as: 'userRequest', foreignKey:
'userRequestId'});
Invitation.belongsTo(models.user, { as: 'userInvited', foreignKey:
'userInvitedId'});
};
return Invitation;
};