node.js - Sequelize.js - "where"子句中连接表中的列

标签 node.js orm sequelize.js

我在 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 大师应该支持以下内容:

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

关于node.js - Sequelize.js - "where"子句中连接表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23652199/

相关文章:

javascript - 我应该在模型或 Controller 中的什么地方编写查询(sequelize)?

sequelize.js - 如何使用包含进行 LEFT OUTER JOIN

node.js - 连接到 MongoDB 中的多个集合

ORM:通过可达性授权

node.js - Puppeteer 错误 : Protocol error (Page. captureScreenshot):目标已关闭

java - Play 2.1-快照: Ebean database updates and deletions don't work in Junit test cases

ruby-on-rails - has_many 关系的动态类名

mysql - 如何在sequelize中使用mysql的curdate()

node.js - Mandrill API 在按计划作业运行时不发送电子邮件

javascript - Jasmine Node 说 "0 tests"当有*有*测试