[英]Sequelize include with multiple where condition
我在使用 Sequelize 和include
遇到了一些問題。 問題是我的模型在子表中使用了兩個主鍵。
所以它就像這個父表 User : Id, ...
Post : Id, UserId(foreign key, binds to user id), ... Post Hash Tag : HashTag, PostId(foreign key, binds to Post id), UserId(foreign key, binds to user id of Post table)
所以表層次結構看起來像這個用戶 - 發布 - 發布哈希標簽
現在當我嘗試這樣做時
Post.findAll(
include: {
model: post hash tag
}
)
然后它只搜索帖子哈希標簽的帖子哈希標簽表的帖子ID等於帖子表的帖子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(...)
我自己找到了答案... 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'))
這會起作用。 括號中使用的表和列的物理名稱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.