I'll preface this by saying I think my model associations may be incorrect
Basically what i'm trying to do is is return an array of all Employees for a company.
Profiles are linked to Locations through Employees.
Below is my code.
The query:
Location.findAll({
where: { companyId: user.profile.companyId },
include: [
{
model: Employee
}
]
})
This generates the error "employee is not associated to location!"
.
My models:
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"
})
EDIT:
Adding Location.hasMany(Employee) allows me to do the query however it still requires a for loop within another for loop to get the correct data structure needed.
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
The query below returns what exactly as is however its only for a single location. I need to run the same query but for multiple locations.
Employee.findAll({ where: { locationId }, include: [Profile, Location] })
You've specified that Location belongsToMany Locations, but you've failed to specify the other way around. You should specify that a Location hasMany Employees.
Specifying Employee.belongsTo(Location)
allows you to include related Locations with Employees. Specifying Location.hasMany(Employee)
allows you to include related Employees with Locations.
I was able to recreate your problem and fix it with this line.
Location.hasMany(Employee, {
//...
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.