【问题标题】:filter Sequelize belongsToMany get<Association> association tablefilter Sequelize belongsToMany get<Association> 关联表
【发布时间】:2018-11-28 00:38:47
【问题描述】:

我正在使用 Sequelize 4.37.10,它运行良好。 不幸的是,我认为文档并不完美。所以它缺少一些描述 belongsToMany 的可能性。

我有以下问题:

我这样定义我的表:

const Department = db.define('department', {
  name: {type: Sequelize.STRING, allowNull: false},
  shortName: {type: Sequelize.STRING, allowNull: false}
})

const Employee = db.define('employee', {
  title: {type: Sequelize.STRING},
  name: {type: Sequelize.STRING, allowNull: false},
  surname: {type: Sequelize.STRING, allowNull: false},
  .
  .
  role: {type: Sequelize.STRING}
})

然后我像这样关联表格:

const EmployeeDepartments = db.define('employeeDepartments', {
  manager: {type: Sequelize.BOOLEAN, allowNull: false}
})

Department.belongsToMany(Employee, {through: EmployeeDepartments})
Employee.belongsToMany(Department, {through: EmployeeDepartments})

现在我想让所有部门员工的经理字段设置为 true。 创建没问题,但是选择对我来说是个问题。

我尝试了以下方法,但没有成功:

department.getEmployees({where: {manager: true}})

我也想过范围,但我不知道如何正确设计。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: javascript mysql sequelize.js has-and-belongs-to-many


    【解决方案1】:
    department.getEmployees({where: {manager: true}})
    

    用这个改变这个代码。

    department.getEmployees(      
      include:{
        model: employeedepartments, // your employee departments model name
        {where: {manager: true},      
        required:true, 
      }
    })
    

    您只需在查询中添加包含

    【讨论】:

    • include 需要一个数组
    【解决方案2】:

    有趣的是,我只是在寻找完全相同的东西,唯一的结果是你几个小时前的问题......

    我现在已经解决了,你需要的是:

    department.getEmployees({ through: { where: { manager: true } } })
    

    您还可以获取department 的所有员工,其中您只有id:

    const department = Department.build( { id: departmentId } );
    // proceed as above
    

    【讨论】:

    • 不错!很遗憾知道Sequelize docs 没有告诉任何关于through 选项的信息。谢谢!在我看来,第二行代码使用Department.findById(departmentId) 更容易
    • 这种方法的问题是你击中了数据库。 build 没有。
    • 另外,您可能会遇到无法从结果员工中真正删除关联字段departmentEmployee 的问题(请参阅此问题:github.com/sequelize/sequelize/issues/3664)。我用employees.forEach( e =&gt; delete e.dataValues['department_employee'] ) 解决了这个问题
    【解决方案3】:

    我自己搜索了一段时间后找到了一个非常简单的答案。

    当使用belongsToMany时,Sequelize 确实使用连接从第二个表中获取数据(我知道)。

    我可以选择使用以下语法:

    department.getEmployees({where: {'$employeeDepartments.manager$': true}})
    

    我从谷歌的一个页面上找到了,但不幸的是我丢失了网址。 也许这可以帮助遇到类似问题的人。

    【讨论】:

      猜你喜欢
      • 2019-03-13
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多