我的 MSQL 表中有这两个模型之间的多对多关系:



我正在使用 sequelize 来建立这样的关系:

关系员工 > 地点

 Employee.associate = function (models) {
   models.Employee.belongsToMany(models.Venue, { through: 'EmployeeVenues' })
 }

关系 field > 员工
 Venue.associate = function (models) {
    models.Venue.belongsToMany(models.Employee, { through: 'EmployeeVenues' })
 }

Sequelize 文档



这是正确的工作,当我启动我的 Sequelize 时,它​​会创建一个名为 EmpoyeeVenues 的新表,并使用正确的外键作为复合键。但是,当我查询 getVenues 时,它不会返回预期的输出。相反,它也返回关联的表值,这是我不想要的。

查询以获取属于 id 等于 1 的员工的所有场所
router.get('/api/v1/users/:employee_id/venues', (request, response) => {
  var employeeId = request.params.employee_id;

  models.Employee.findOne({
    where: {id: employeeId}
  }).then((employee) => {

    if(!employee) { return response.status(400).send("Employee doesnt have a venue registered yet.")}
    var venues = employee.getVenues().then((venues) => {
    response.status(200).send(venues);
  })
})
});

响应结果
[
    {
        "id": 1,
        "capacity": "11",
        "venue_name": "Club Fix",
        "venue_description": "Club in Tilburg",
        "EmployeeVenues": {
            "employee_id": 1,
            "venue_id": 1
        }
    },
    {
        "id": 2,
        "capacity": "400",
        "venue_name": "Club Vie",
        "venue_description": "Club in Rotterdam",
        "EmployeeVenues": {
            "employee_id": 1,
            "venue_id": 2
        }
    }
]

问题



更新



https://github.com/sequelize/sequelize/issues/2143
    User.find({
    where: {id: userId}, attributes: userFields,
    include: [
      {model: db.Role, attributes: roleFields, through: {attributes: []}}
    ]
});

但它与最新的 Sequelize 文档中记录的版本不匹配,至少应该是这样。
User.findAll({
  include: [{
    model: Project,
    through: {
      attributes: ['createdAt', 'startedAt', 'finishedAt'],
      where: {completed: true}
    }
  }]
});

或者甚至在 reference documentation: 上简单说明
user.getPictures() // gets you all pictures

最佳答案

更新



https://github.com/sequelize/sequelize/issues/2143

    User.find({
    where: {id: userId}, attributes: userFields,
    include: [
      {model: db.Role, attributes: roleFields, through: {attributes: []}}
    ]
});

但它与最新的 Sequelize 文档中记录的版本不匹配,至少应该是这样。
User.findAll({
  include: [{
    model: Project,
    through: {
      attributes: ['createdAt', 'startedAt', 'finishedAt'],
      where: {completed: true}
    }
  }]
});

或者甚至在 reference documentation: 上简单说明
user.getPictures() // gets you all pictures

关于mysql - Sequelize 在查询中返回连接表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47961046/

10-16 15:46