我想我的模型关联可能是不正确的
基本上,我要做的是为一家公司返还一系列员工。
-
获取所有具有相同公司ID的位置
-
使用这些位置,获取与locationid关联的所有配置文件。
配置文件通过员工链接到位置。
下面是我的代码。
查询:
Location.findAll({
where: { companyId: user.profile.companyId },
include: [
{
model: Employee
}
]
})
这会产生错误
"employee is not associated to location!"
.
我的模型:
Employee.belongsTo(Profile)
Employee.belongsTo(Location)
Profile.belongsTo(Company)
Location.belongsTo(Company)
Profile.belongsToMany(Location, {
through: Employee,
foreignKey: "profileId"
})
Location.belongsToMany(Profile, {
through: Employee,
foreignKey: "locationId"
})
编辑:
添加location.hasmany(employee)允许我执行查询,但是它仍然需要在另一个for循环中使用for循环才能获得所需的正确数据结构。
const locations = await models.Location.findAll({
where: { companyId: user.profile.companyId },
include: [{ model: models.Profile }]
})
const response = []
locations.forEach(location => {
location.profiles.forEach(profile => {
response.push({ location, profile })
})
})
return response
下面的查询只返回一个位置的确切内容。我需要对多个位置运行相同的查询。
Employee.findAll({ where: { locationId }, include: [Profile, Location] })