我在使用带有 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/