我想知道如何在连接中选择 ON
子句。我有两个表,packages
和 users
。 package
表有两个字段/列(owner_id、helper_id),它们是同一表 users
的外键。我想要一个用于加入 packages.owner_id = users.id
和 packages.helper_id = users.id
的位置。这是我所拥有的:
models.Packages.findAll({
where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
include: [{
model: models.Users,
attributes: { exclude: ['password'] },
where: ['helper_id = id']
}],
limit: 5,
order: [["id","DESC"]]
})
还有另一个
models.Packages.findAll({
where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
include: [{
model: models.Users,
attributes: { exclude: ['password'] },
where: ['owner_id = id']
}],
limit: 5,
order: [["id","DESC"]]
})
但我收到此错误:
Unhandled rejection Error: Support for literal replacements in the `where` object has been removed
请帮忙?
最佳答案
我喜欢 Shahar Hadas
的回答,但我确实找到了如何解决我想做的事情。
基本上,我必须定义具有特定别名的关系/关联(注意 as
属性):
models.Users.hasMany(models.Packages, { foreignKey: 'owner_id', sourceKey: 'id' });
models.Users.hasMany(models.Packages, { foreignKey: 'helper_id', sourceKey: 'id' });
models.Packages.belongsTo(models.Users, { as: 'owner', foreignKey: 'owner_id', targetKey: 'id' });
models.Packages.belongsTo(models.Users, { as: 'helper', foreignKey: 'helper_id', targetKey: 'id' });
然后当我查询时,我可以选择我想要的别名:
models.Packages.findAll({
where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
include: [{
model: models.Users,
as: 'owner',
attributes: { exclude: ['password'] }
}],
limit: 5,
order: [["id","DESC"]]
})
或
models.Packages.findAll({
where: (!package_id ? { owner_id } : { owner_id, id: { [Op.lt]: package_id } }),
include: [{
model: models.Users,
as: 'helper',
attributes: { exclude: ['password'] }
}],
limit: 5,
order: [["id","DESC"]]
})
关于javascript - Sequelize JS - 在连接中选择 On 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56082518/