我正在尝试将我的模型设计为从party表到attendee表和item表都有关联。这样我就可以使用party\u id查询这两个表。
很明显我没有走对这条路…你有没有想过我会错在哪里?
提前谢谢!
政党模式
module.exports = function(sequelize, DataTypes) {
var Party = sequelize.define("Party", {
eventName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
AuthenticationId: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
eventAddress: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
eventDate: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
eventTime: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
eventDescription: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
displayName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
}
});
Party.associate = function(models) {
Party.hasMany(models.Attendee, {
foreignKey: {
allowNull: false
},
onDelete: "cascade"
});
};
return Party;
};
与会者模型:
module.exports = function(sequelize, DataTypes) {
var Attendee = sequelize.define("Attendee", {
AuthenticationId: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
displayName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
}
});
Attendee.associate = function(models) {
Attendee.hasMany(models.Item, {
foreignKey: {
allowNull: false
},
onDelete: "cascade"
});
};
Attendee.associate = function(models) {
Attendee.belongsTo(models.Party, {
foreignKey: {
allowNull: false
},
onDelete: "cascade"
});
};
return Attendee;
};
项目模型
module.exports = function(sequelize, DataTypes) {
var Item = sequelize.define("Item", {
itemName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
qtyRequested: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
len: [1]
}
},
qtyCommited: {
type: DataTypes.INTEGER,
allowNull: true,
validate: {
len: [1]
}
},
hostAdded: {
type: DataTypes.BOOLEAN,
allowNull: true,
validate: {
len: [1]
}
},
AuthenticationId: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
},
displayName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [1]
}
}
});
Item.associate = function(models) {
Item.belongsTo(models.Attendee, {
foreignKey: {
allowNull: false
},
onDelete: "cascade"
});
};
return Item;
};
这是返回错误的查询:
app.get("/parties/:id", (req, res) => {
db.Party.findOne({
where: { id: req.params.id },
include: [
{
model: db.Attendee,
include: [
{
model: db.Item
}
]
}
]
})
.then(party => {
console.log(party)
})
.catch(function(error) {
console.log(error);
});
});
错误:
SequelizeEagerLoadingError: Item is not associated to Attendee!
2条答案
按热度按时间ckocjqey1#
真正的问题是:
解决方案:
pobjuy322#
问题已解决:为了实现我的目标,我必须将我的关联定义如下:
派对模式:
与会者模型:
项目模型:
我的查询改为: