Mysql 续集-如何让所有地点的所有员工
我会先说我认为我的模型关联可能是错误的 基本上,我要做的是返回一个公司所有员工的数组Mysql 续集-如何让所有地点的所有员工,mysql,node.js,sequelize.js,Mysql,Node.js,Sequelize.js,我会先说我认为我的模型关联可能是错误的 基本上,我要做的是返回一个公司所有员工的数组 获取具有相同companyId的所有位置 使用这些位置,将所有配置文件绑定到locationId 配置文件通过员工链接到位置 下面是我的代码 查询: Location.findAll({ where: { companyId: user.profile.companyId }, include: [ { model:
- 获取具有相同companyId的所有位置
- 使用这些位置,将所有配置文件绑定到locationId
Location.findAll({
where: { companyId: user.profile.companyId },
include: [
{
model: Employee
}
]
})
这将生成错误“员工未与位置关联!”
我的模型:
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] })
您已将该位置指定为多个位置,但未能指定其他位置。您应该指定一个位置有许多员工 指定
Employee.belongsTo(位置)
允许您包括与员工相关的位置。指定Location.hasMany(Employee)
允许您将相关员工包括在位置中
我可以重新创建您的问题并用这行代码修复它
Location.hasMany(Employee, {
//...
})
尝试使用'hasMany'指令将Location与Employee之间的关系添加到:Location.hasMany(Employee)@FedericoB。在添加了您提到的其他关系之后,我能够让它正常工作。您能检查我在原始问题中的编辑,并让我知道是否有办法仅使用sequelize解决此问题吗?尝试在“where对象”({where:{…},raw:true})之后添加“raw:true”,并检查返回的新结构是否更适合您。您还可以设置“raw”属性并从上一个示例中删除where条件。如果我没有错,您可以检索与位置关联的员工列表,您可以检查我在问题底部的编辑吗?有没有更好的方法查询多个地点的多个员工?如果您正在寻找员工,应该运行Employee.findAll。使用何处筛选所需的内容。其中:{locationId:[…]}。我正在根据未知的位置ID寻找员工。基本上每个地点都有他们所有的位置,不过我还是能让它工作。我将sequelize与graphql结合使用,我认为我的graphql模式不正确。