我想 通过两个标识符 找到一个项目。一个标识符是该项目的主键,另一个标识符是来自不同表的另一个项目的主键,与第一个具有多对多关系。我希望请求仅在存在带有 id1
的项目并且与来自不同表的 id2
的现有项目存在关系时才返回数据。
const Item1 = sequelize.define('item1', {})
const Item2 = sequelize.define('item2', {})
const Relation = sequelize.define('relation', {})
Item2.belongsToMany(Item1, { through: Relation })
// the givens are id1 of Item1 and id2 of related Item2
const data = await Item1.findOne({
where: { id: id1 },
include: [
{
model: Item2,
attributes: [],
required: true,
through: {
attributes: [],
where: { item2Id: id2 }
}
}
]
})
通过将
attributes
设置为空数组,我希望 ORM 不会获取任何相关数据,因为我唯一担心的是相关对象存在。有没有更干净的方法来实现这一目标?
干杯
最佳答案
const Item1 = sequelize.define('item1', {})
const Item2 = sequelize.define('item2', {})
const Relation = sequelize.define('relation', {})
Item2.belongsToMany(Item1, { through: Relation })
Item1.hasMany(Relation, {foreignKey1, constraints: false});
Relation.belongsTo(Item1, {foreignKey1, constraints: false});
Item2.hasMany(Relation, {foreignKey2, constraints: false});
Relation.belongsTo(Item2, {foreignKey2, constraints: false});
const data = await Item1.findOne({
where: { id: id1 },
include: [
{
model: Relation,
attributes: [],
required: true,
include: [
{
model: Item2,
attributes: [],
required: true,
where: { item2Id: id2 }
}
]
}
]
});
关于node.js - Sequelize JS,仅当存在多对多相关实体时才 findOne,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53417196/