2
votes

I am trying to join two tables using Sequelize's include as such:

  models.user.findAll({include: {model: models.boardMember, required:true}})
    .then(function(board) {
       console.log(board);
       res.render('contact', { title: 'Kontakt', board: board });
    });

My models look like this using the sequelize express example:

User (it doesn't quite feel right having the hasMany here instead of in boardMembers, but I didn't want to have the foreign key field in the users table)

module.exports = function(sequelize, DataTypes) {
  var user = sequelize.define('user', {
    //lots of normal user fields(username, password, access...
   }, {
     classMethods: {
       associate: function(models) {
         user.hasMany(models.boardMember, {
           foreignKey: {
             allowNull: false
           }
         });
       }
     }
  });

  return user;
};

boardMember

module.exports = function(sequelize, DataTypes) {
  var boardMember = sequelize.define('boardMember', {
    post: {
      type: DataTypes.STRING,
      unique: false,
      allowNull: false
    }
  });
  return boardMember;
};

I then want to access the data returned in a table using handlebars:

{{#each board}}
  <tr>
    <td>{{boardMembers.post}}</td>
    <td>{{firstName}} {{surName}}</td>
    <td>{{email}}</td>
  </tr>
{{/each}}

Here is where I get it wrong(I think). The names and email appear, but not the post. I've tried using only post as well but to no avail. This is odd I think because the query that is generated looks like this (I removed the createdAt and updatedAt columns to make it shorter for you to read):

SELECT 
    `user`.`id`, `user`.`username`, `user`.`password`, 
    `user`.`firstName`, `user`.`surName`, `user`.`email`, `user`.`access`,  
    `boardMembers`.`id` AS `boardMembers.id`, `boardMembers`.`post` AS `boardMembers.post`,  
    `boardMembers`.`userId` AS `boardMembers.userId` 
FROM 
    `users` AS `user` 
INNER JOIN 
    `boardMembers` AS `boardMembers` ON `user`.`id` = `boardMembers`.`userId`;

The console.log outputs something like this(the data obviously changed):

[ Instance {
dataValues:
 { id: 2,
   username: 'username',
   password: 'hashedPassword',
   firstName: 'User',
   surName: 'Name',
   email: '[email protected]',
   access: '0',
   boardMembers: [Object] },
...
]

Any help is much appreciated!

Thanks,

Freece

1

1 Answers

0
votes

Per the sequelize documentation the value for the include attribute is a list.

You can try with the special value include: [{ all: true, nested: true }] and see if it works for you.

Additionally you have a problem with your template becuase you have stablished a one to many relation and therefore the boardMemebers attribute of model instances are arrays.