【问题标题】:Sequelize.js - column from junction table in "where" clauseSequelize.js - “where”子句中联结表中的列
【发布时间】:2014-07-02 08:43:43
【问题描述】:

我在 Node.js 有一个项目,使用 Sequelize 作为 ORM。

我创建了多对多关系,我需要使用“where”子句中联结表中的一些列进行查询。

我有以下型号:

sequelize.define("User", {
    //some values
}, {
    "classMethods" : {
        "associate" : function (models) {
            User.hasMany(models.Book, { "through" : models.BorrowedBook });
        }
    }
});

sequelize.define("Book", {
    //some values
}, {
    "classMethods" : {
        "associate" : function (models) {
            Book.hasMany(models.User, { "through" : models.BorrowedBook });
        }
    }
});

sequelize.define("BorrowedBook", {
        //some other values
        "returnedAt" : DataTypes.DATE
    }
);

如何在“where”子句中使用“BorrowedBook”中的列?

例如我想让所有用户热切地加载至少有 1 本书并且“BorrowedBook.returnedAt”为空。

有没有办法,像这样的?

db.Book
    .find({
        "include" : [
            db.User,
            { "model" : db.BorrowedBook, "where" : { "borrowedAt" : null } }
        ]
    })

【问题讨论】:

  • 如果你使用 sequelize 的 master 分支,你应该可以做类似{model: db.User, through: { where: { borrowedAt: null } } }

标签: node.js orm sequelize.js


【解决方案1】:

除非您实际直接设置了与直通模型的关系,否则您不能像那样包含直通模型,但您仍然无法完成您想要的。

最新的 Sequelize 大师应该支持这样的:

db.Book.find({
  include: [
    {model: db.User, through: {
      where: {borrowedAt: null}
    }
  ]
})

【讨论】:

  • 我无法让它工作,我已经尝试使用 v1.7.5 和 v2.0.0.dev11 并且它们都没有工作。 “通过”索引无效。
  • 啊,那么它没有被属性实现所覆盖。在 GitHub 上打开功能请求。
  • 我已经打开了一个功能请求。对于任何其他感兴趣的人,这里是链接:github.com/sequelize/sequelize/issues/1775
猜你喜欢
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 2016-09-21
  • 2016-02-05
  • 2015-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多