序列化JS,仅当存在多对多相关实体时才查找

时间:2018-11-21 17:03:53

标签: node.js sequelize.js

我想通过两个标识符找到一个项目。一个标识符是该项目的主键,另一个标识符是来自不同表的另一个项目的主键,该表与第一个有多对多关系。我希望只有在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不会获取任何相关数据,因为我唯一关心的是相关对象存在。

有没有更清洁的方法来实现这一目标?

欢呼

1 个答案:

答案 0 :(得分:1)

  1. 我认为我们可以使用此功能添加PR。
  2. 现在您可以执行以下操作:

    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 }
                    }
                ]
            }
        ]
    });