Phorce Phorce -4 years ago 132
Node.js Question

NodeJS Squalize -- Relationships without including at sign in

I'm using sequalization and relationships for the users. So for example, a user can be a customer or can be an employee.

I set this through the following way:

where: { id: id },
include: [
limit: 1
}).then(function(result) {

done(null, result);


The main issue is that not all users are customers or employees but it seems the only way to access the relationships is using the
at the state of login.

What I want to be able to do is not include the relationship at login and just use
and it finds the relationship, similar to what I would do in Laravel

Answer Source

What you can do is use the instance.getAssociation() method in order to retrieve associated model

        // here you obtain customer assigned to user with id = 1


I suggest you follow your first concept. On login perform the find query with include option

models.users.findById(id, {
    include: [ models.customers ]
}).then(function(user) {
    if ( user.customer ) console.log('User is a customer');
    else console.log('User is not a customer'); 

In order to define if user is a customer you need to perform a query returning the customer object, otherwise you do not have any option to recognise the type of user. I can also suggest you add some type field to user model which could be some ENUM with values like customer, employee, regular defining what kind of user it is. It would be set to proper value when creating new instance e.g.

        name: 'some name',
        customer: {
            // some customer attributes
        type: 'customer'
    }, {
        include: [ models.customers ]
}).then((user) => { console.log(user); });

If you follow this way then you can check user's status at any time by accessing user.type which would be one of above ENUM values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download