Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a working sample of how to user Sequelize to get all <code>Books</code> by an <code>Author</code> with a certain last name. It looks quite a bit more complicated than it is, because I am defining the Models, associating them, syncing with the database (to create their tables), and then creating dummy data in those new tables. Look for the <code>findAll</code> in the middle of the code to see specifically what you're after.</p> <pre><code> 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') }); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload