include - Sequelize 包含多个 where 条件

标签 include sequelize.js composite-primary-key

我在使用带有 include 的 Sequelize 时遇到了一些问题.问题是我的模型在子表中使用了两个主键。

所以它是这样的
父表
用户身份, ...
Post : Id, UserId(外键, 绑定(bind)到用户 id), ...
Post Hash Tag : HashTag, PostId(外键, 绑定(bind)到 Post id), UserId(外键, 绑定(bind)到 Post 表的用户 id)

所以表层次结构看起来像这样
用户 - 帖子 - 帖子哈希标签

现在,当我尝试这样做时,

Post.findAll(
  include: {
    model: post hash tag
  }
)

然后它只搜索 post hash tags 中 post hash tag table 的 post id 等于 post table 的 post id

所以我这样添加
Post.findAll(
  include: {
    model: post hash tag
    where: {
      col1: models.sequelize.where(models.sequelize.col('POST.USER_ID'), '=', models.sequelize.col('POST_HASH_TAG.USER_ID'))
    }
  }
);

然后它会在 'where' 子句中出现 Post.USER_ID 找不到的问题。

如果我将 col1 值更改为 Post.userId 那么现在它解决了上述错误但在“on”子句中给出了另一个错误

你知道我该如何解决这个问题吗?

完整的模型在这里给出

用户
sequelize.define('User', {
    id: { type: DataTypes.STRING(6), field: 'ID', primaryKey : true }
)

发布 - 我知道多个主要声明无法正常工作,所以不要费心考虑太多
sequelize.define('Post', {
    id: { type: DataTypes.STRING(6), field: 'ID', primaryKey: true },
    userId: { type: DataTypes.STRING(6), field: 'USER_ID', primaryKey: true }
)

发布哈希标签
sequelize.define('PostHashTag', {
    postId: { type: DataTypes.STRING(6), field: 'POST_ID', primaryKey: true },
    hashTag: { type: DataTypes.STRING(20), field: 'HASH_TAG', primaryKey: true },
    userId: { type: DataTypes.STRING(6), field: 'USER_ID', primaryKey: true }
  }
)

我使用的查询是
Post.findAll({
  attributes: ['id', 'userId'],
  where: {
    userId: userId,
    id: { $lt: postId }
  },
  include: [{
    model: models.PostHashTag,
    attributes: ['hashTag'],
    where: {
      col1: models.sequelize.where(models.sequelize.col('Post.USER_ID'), '=', models.sequelize.col('PostHashTag.userId'))
  }]).then(...)

最佳答案

我自己找到了答案... col1:

models.sequelize.where(models.sequelize.col('Post.USER_ID'), '=', models.sequelize.col('PostHashTag.userId')) 

这应该是
userId: models.sequelize.where(models.sequelize.col('POST.userId'), '=', models.sequelize.col('POST_HASH_TAG.USER_ID'))

这会奏效。括号中使用的表和列的物理名称

关于include - Sequelize 包含多个 where 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43773765/

相关文章:

express - Sequelize 模型不会在 then block 中返回

sql - T-SQL 唯一标识列作为复合主键的一部分

php - 如何在 Javascript 中引用另一个页面的 ID 作为变量

visual-studio-2008 - Visual Studio 自动包含 (C#)

include() 之前的 PHP 校验和

c++ - #pragma once 和#include 问题

javascript - Sequelize : cannot find module (Model)

node.js - 有没有办法使用 Node.js 在 Sequelize Schema 中的表之间交替?

java - JPA - @EmbeddedId 和 @Id

sql - 在逻辑上确定 SQL 中的组合键