【问题标题】:How to write an Inner Join query using sequelize ORM?如何使用 sequelize ORM 编写内连接查询?
【发布时间】:2021-04-11 17:30:34
【问题描述】:

我的内部连接查询如下所示

SELECT list.id, list.name,
sa.createdBy
FROM list 
INNER JOIN data sa 
               ON sa.listId = list.id 
WHERE sa.type = 'type1'
and sa.data = 'data1'

我正在尝试使用 sequelize ORM 编写上述查询。 我已经编写了以下查询,但它没有给出预期的结果。

list.findAll({
  include: [{
    model: data,
    required: true
    where: {type: 'type1'}
   }]
}).then(list => {
  /* ... */
});

【问题讨论】:

  • 看看这个:stackoverflow.com/q/55354324/10910692。虽然只有一个不被接受的答案,但我认为有一个关于如何加入的参考。似乎您只需要将第二个表放在{} 中,就像第一个表一样,并用逗号分隔。

标签: mysql node.js join orm sequelize.js


【解决方案1】:

您的 where 子句未完全包含您编写的查询

list.findAll({
  include: [{
    model: data,
    required: true,
    where: {
       type: 'type1', // sa.type = 'type1'
       data: 'data1', // sa.data = 'data1'
    },
   }]
}).then(lists => { // renamed to lists to prevent shadowing the "list" model variable
  /* ... */
});

【讨论】:

  • 我需要在哪里包含ON sa.listId = list.id?另外,如何获取sa.createdBy
  • 如果您的data 表正确关联到模型定义中的list 表,那么“包含”会为您执行ON 部分。不知道你的list和data是一对一还是一对多的关系,但是如果你想让我看,你可以粘贴你的模型代码。现在,您的查询将带回两个表的所有属性,因此如果createdBydata 表中的一列,它应该存在。这取决于您的模型如何:一对一或一对多。我会为你展示每一个。
  • then(lists => { if (lists.length) { const first = lists[0]; const firstCreatedByOneToOne = first.data.createdBy; // one-to-one const firstCreatedByOneToMany = first.data[0].createdBy; // one-to-many, gets createdBy of first joined record } });
猜你喜欢
  • 1970-01-01
  • 2014-12-24
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多