node.js - Sequelize JS,仅当存在多对多相关实体时才 findOne

标签 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 不会获取任何相关数据,因为我唯一担心的是相关对象存在。

有没有更干净的方法来实现这一目标?

干杯

最佳答案

  • 我认为我们可以用这个功能添加 PR。
  • 现在你可以这样做:
    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/

    相关文章:

    javascript - 如何通过 JavaScript 或 Node.js 强制将 PDF 从文件夹下载到浏览器/用户?

    node.js - Sequelize - 从外部表中关联和选择

    javascript - 带 socket.io 的 Node.js : TypeError: Obj has no method 'on' at new Manager

    node.js - pm2 restart 和 pm2 reload 有什么区别

    javascript - 我应该制作自己的graphql风格的api但只能使用sequelize吗?

    node.js - Sequelize.js:findById() 未找到数据

    node.js - 带有长字符串错误的 Sequelize/繁琐的创建/更新记录 : read ECONNRESET

    node.js - 传递给 findOne 的参数必须是一个选项对象,如果您希望传递单个主键值,请使用 findById 我在 Sequelize 中已完成此操作

    node.js - 如何访问 sails.services.*?

    javascript - 解析 Node Express 路由中带有特殊字符的 URL