Sequelize 在查询中返回连接表 [英] Sequelize returns join table in query

查看:44
本文介绍了Sequelize 在查询中返回连接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<块引用>
  • 场地 - 代表可以有多个所有者(员工)的场地
  • 员工 - 代表一名员工,可以是 CEO 或销售员工,也可以是任何身份.

我正在使用 像这样设置关系:

关系员工 > 地点

 Employee.associate = 函数(模型){models.Employee.belongsToMany(models.Venue,{通过:'EmployeeVenues'})}

关系场所 > 员工

 Venue.associate = 函数(模型){models.Venue.belongsToMany(models.Employee,{通过:'EmployeeVenues'})}

续集文档

<块引用>

根据 Sequelize docs 它将创建一个名为 EmployeeVenues 的新模型等效的外键employee_id 和venue_id.需要定义通过.Sequelize 之前会尝试自动生成名称,但这并不总是导致最合乎逻辑的设置.这会将方法 getVenues、setVenues、addVenue、addUsers 添加到 Employee.

<小时>

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

<小时>

查询一个id等于1的员工的所有场地

<小时>

router.get('/api/v1/users/:employee_id/venues', (request, response) => {var employeeId = request.params.employee_id;模型.员工.findOne({其中:{id:employeeId}}).then((员工) => {if(!employee) { return response.status(400).send("员工还没有注册场地.")}varvenues = employee.getVenues().then((venues) => {response.status(200).send(venues);})})});

响应结果

<小时><预><代码>[{身份证":1,"容量": "11","venue_name": "俱乐部修复","venue_description": "蒂尔堡俱乐部",员工场所":{"employee_id": 1,场地 ID":1}},{身份证":2,"容量": "400","venue_name": "Club Vie","venue_description": "鹿特丹俱乐部",员工场所":{"employee_id": 1,场地 ID":2}}]

问题

<块引用>

为什么 EmployeeVenues 包含在 Sequelize 提供的这个查询中?以及如何防止 EmployeeVenues 包含在响应中?


更新

<块引用>

根据 2014 年创建的 Sequelize github 页面上的一个问题,有一个可行的解决方案

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

 User.find({其中:{id:userId},属性:userFields,包括: [{模型:db.Role,属性:roleFields,通过:{属性:[]}}]});

<小时>

但它与最新的 Sequelize 文档中记录的版本不匹配,至少应该如此.

<小时>

User.findAll({包括: [{型号:项目,通过: {属性:['createdAt','startedAt','finishedAt'],其中:{完成:真实}}}]});

<小时>

或者甚至在参考文档中简单说明:

<小时>

user.getPictures()//获取所有图片

解决方案

更新

<块引用>

根据 2014 年创建的 Sequelize github 页面上的一个问题,有一个可行的解决方案

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

 User.find({其中:{id:userId},属性:userFields,包括: [{模型:db.Role,属性:roleFields,通过:{属性:[]}}]});

<小时>

但它与最新的 Sequelize 文档中记录的版本不匹配,至少应该如此.

<小时>

User.findAll({包括: [{型号:项目,通过: {属性:['createdAt','startedAt','finishedAt'],其中:{完成:真实}}}]});

<小时>

或者甚至在参考文档中简单说明:

<小时>

user.getPictures()//获取所有图片

I've got a many-to-many relation in my MSQL table between these two model:

  • Venue - Representing a venue which can have multiple owners (employees)
  • Employee - Representing an employee which can be either a ceo or sales employee or whatsoever.

I am using to set up the relations like so:

Relation Employee > Venue

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

Relation Venue > Employee

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

Sequelize docs

According to the Sequelize docs it will create a new model called EmployeeVenues with the equivalent foreign keys employee_id and venue_id. Defining through is required. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups. This will add methods getVenues, setVenues, addVenue, addUsers to Employee.


And this is correctly working, when I fire up my Sequelize it creates a new table called EmpoyeeVenues with the correct foreign keys as a compound key. However when I query getVenues it does not return the expected output. Instead, it's returning the associated table values as well, which I don't want.


Query to get all venues belonging to an employee with id equal 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);
  })
})
});

Response Result


[
    {
        "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
        }
    }
]

Question

Why is EmployeeVenues included in this query provided by Sequelize? And How can I prevent EmployeeVenues to be included in the response?


Update

According to a issue on the Sequelize github page which was made in 2014 there is a solution that works

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

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


But it does not match the documented version in the Sequelize documentation which is up-to-date, at least it should be.


User.findAll({
  include: [{
    model: Project,
    through: {
      attributes: ['createdAt', 'startedAt', 'finishedAt'],
      where: {completed: true}
    }
  }]
});


Or even simple stated on the reference documentation:


user.getPictures() // gets you all pictures

解决方案

Update

According to a issue on the Sequelize github page which was made in 2014 there is a solution that works

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

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


But it does not match the documented version in the Sequelize documentation which is up-to-date, at least it should be.


User.findAll({
  include: [{
    model: Project,
    through: {
      attributes: ['createdAt', 'startedAt', 'finishedAt'],
      where: {completed: true}
    }
  }]
});


Or even simple stated on the reference documentation:


user.getPictures() // gets you all pictures

这篇关于Sequelize 在查询中返回连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆