1

I'm currently using Sequelize =>4.0 and finding having 2 models link together doesn't work how i assumed it would.

Basically, i have 2 models: user & punch.

user: id name email

punch: id userId <- user id time status

I would like to show the list of users and their linked punches.

Here is my .associate function under each model:

users.associate = function (models) { // eslint-disable-line no-unused-vars
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/

    users.hasMany( models.punch, {foreignKey: 'id'} );
};


punch.associate = function (models) { // eslint-disable-line no-unused-vars
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/

    punch.belongsTo(models.users, {foreignKey: 'userId', targetKey: 'id'});
};

Is this the correct way? Is there anything else i need to do. When i view the user GET request, i'm not seeing anything other than the user data.

Any help would be greatly appreciated :)

tutchmedia
  • 139
  • 2
  • 12

1 Answers1

1

You'll need to update your before hooks, as per feathers-sequelize docs:

// users.hooks.js

associationHook(context){
    const PunchModel = context.app.services.punch.Model;

    context.params.sequelize = {
        include: [{ model: PunchModel }]
    }
}

module.exports = {
    before: {
        (...)
        find: [associationHook],
        (...)
    }
    (...)
};

You'll want to do this for find/get and any other ones you want the association data to be returned.

There's also fastJoin and populate in feathers-hooks-common.

YiSh
  • 347
  • 1
  • 4
  • 12
  • So what is the difference between sequelize association and fastJoin? Speed? – musicformellons May 29 '18 at 13:14
  • Sequelize associations are for modifying the query and retrieving the association through sql. The two hooks are more about creating associations after the main query (simplifying here) and work around service associations rather than pure sql. Some things aren't easily (or at all) doable in a single query. – YiSh May 30 '18 at 15:20