首页 文章

Sequelize包含多个where条件

提问于
浏览
1

使用sequelize和'include'有点问题 . 问题是我的模型在子表中使用了两个主键 .

所以它就像这个父表用户:Id,...
发布:Id,UserId(外键,绑定到用户ID),... Post Hash标签:HashTag,PostId(外键,绑定到Post id),UserId(外键,绑定到Post表的用户ID)

因此,表层次结构看起来像这个用户 - post-post哈希标记

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

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

那么它只搜索post hash标签,其中post hash标签表的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'))
}
}
)

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

如果我将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(...)

1 回答

  • 1

    我自己找到了答案... 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'))
    

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

相关问题