Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize find based on association

How would I use Sequelize to find all people where a column in the relation satisfies a condition?

An example would be to find all Books whose author's last name is 'Hitchcock'. The book schema contains a hasOne relation with the Author's table.

Edit: I understand how this could be done with a raw SQL query, but looking for another approach

like image 342
futbolpal Avatar asked Sep 16 '13 22:09

futbolpal


People also ask

How do I use association in Sequelize?

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.

What is findByPk?

findByPk() Finds a single active record with the specified primary key. CActiveRecord.


1 Answers

Here's a working sample of how to user Sequelize to get all Books by an Author 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 findAll in the middle of the code to see specifically what you're after.

    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')         });   } 
like image 167
c.hill Avatar answered Sep 22 '22 22:09

c.hill