根据关联进行search查找

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

一个例子是find作者姓氏“希区柯克”的所有书籍。 书籍模式包含与作者表的hasOne关系。

编辑:我明白这可以做一个原始的SQL查询,但寻找另一种方法

下面是一个如何使用Sequelize获取具有某个姓氏的Author所有Books的工作示例。 它看起来比现在复杂得多,因为我正在定义模型,将它们关联起来,与数据库同步(创build表),然后在这些新表中创build虚拟数据。 在代码中间寻找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') }); }