代码之家  ›  专栏  ›  技术社区  ›  KFE

续集-如何让所有地点的所有员工

  •  0
  • KFE  · 技术社区  · 6 年前

    我想我的模型关联可能是不正确的

    基本上,我要做的是为一家公司返还一系列员工。

    • 获取所有具有相同公司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] })
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Jemi Salo    6 年前

    您已经指定了属于多个位置的位置,但未能指定相反的位置。您应该指定一个地点有许多雇员。

    指定 Employee.belongsTo(Location) 允许您包含与员工相关的位置。指定 Location.hasMany(Employee) 允许您包含具有位置的相关员工。

    我能重现你的问题并用这条线解决它。

    Location.hasMany(Employee, {
        //...
    })