如何使用Sequelize查找关系中某列满足条件的所有人?

例如,找到所有作者姓"希区柯克"的书.图书模式包含与作者表的hasOne关系.

编辑:我理解如何使用原始SQL查询来实现这一点,但正在寻找另一种方法

推荐答案

下面是一个工作示例,演示了如何通过用户续集,通过一个有特定姓氏的Author获得所有Books个.它看起来比实际情况要复杂得多,因为我正在定义模型,关联它们,与数据库同步(创建它们的表),然后在这些新表中创建虚拟数据.在代码的中间寻找findAll个,看看你到底在追求什么.

    module.exports = function(sequelize, DataTypes) {

    var Author = sequelize.define('Author', {

        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        firstName: {
            type: DataTypes.STRING
        },
        lastName: {
            type: DataTypes.STRING
        }

    })

    var Book = sequelize.define('Book', {

        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true
        },
        title: {
            type: DataTypes.STRING
        }

    })

    var firstAuthor;
    var secondAuthor;

    Author.hasMany(Book)
    Book.belongsTo(Author)

    Author.sync({ force: true })
        .then(function() {
            return Book.sync({ force: true });
        })
        .then(function() {
            return Author.create({firstName: 'Test', lastName: 'Testerson'});
        })
        .then(function(author1) {
            firstAuthor=author1;
            return Author.create({firstName: 'The Invisible', lastName: 'Hand'});
        })
        .then(function(author2) {
            secondAuthor=author2
            return Book.create({AuthorId: firstAuthor.id, title: 'A simple book'});
        })
        .then(function() {
            return Book.create({AuthorId: firstAuthor.id, title: 'Another book'});
        })
        .then(function() {
            return Book.create({AuthorId: secondAuthor.id, title: 'Some other book'});
        })
        .then(function() {
            // This is the part you're after.
            return Book.findAll({
                where: {
                   'Authors.lastName': 'Testerson'
                },
                include: [
                    {model: Author, as: Author.tableName}
                ]
            });
        })
        .then(function(books) { 
            console.log('There are ' + books.length + ' books by Test Testerson')
        });
  }

Node.js相关问答推荐

如何使用多个OR参数从多个集合聚合

Jest由于UUID而无法解析测试,即使在Jest中启用ESModule支持后也是如此

类扩展值[object object]不是构造函数或null

Inno Setup如何在现有文本文件中追加新内容

Rest-Api动态图像路径和Express除非

如何从 Mongo Atlas 触发器向 GCP PubSub 发出经过身份验证的请求

如果我在 tsx 文件中使用了use client,ssr 会如何发生?

try 使用 pdf.js 时 pdf.getPage 不是函数

dayjs的isSameOrAfter方法未按预期工作

mongoose findOneAndUpdate 不更新数据库

在快速路由中使用 axios 会在数据字段中返回特殊字符而不是 json

在 nodejs 中使用 multer 上传文件返回未定义的 req.file 和空的 req.body

使用react 组件加载特定 DIV 而无需重新加载整个页面

如何解决这个关于 TaskRunner 的 Node/Express 代码问题?

如果 express.js (node.js) http 请求在完成之前关闭会发生什么?

NodeJs 过滤掉目录异步

使用服务帐户将 Firebase 应用程序部署到 Heroku(使用 dotenv 的环境变量)

JSHint 是否支持异步/等待?

mongo 可以 upsert 数组数据吗?

webpack-dev-server 找不到模块webpack