Himmators Himmators - 5 months ago 10
Node.js Question

Find items by association?

I have two associated data-objects, User and userAttributes. User hasMany userAttributes.

I wish to find a user that has a related value in userAttributes. First I thought I could search the associated table like this:

userAttribute.findOrCreate({where: {'name': 'fbprofile', 'value': profile.id }})
.spread((userAttribute, created) => {
if(created){...}else{...}
})


but I realized I still need to lookup the user based on the association.

Is there a way to find a record based on the association?

Answer

You can easily use eager loading for that.

userAttribute.findOrCreate({
    where: {'name': 'fbprofile', 'value': profile.id },
    include: [ User ]
})
.spread((userAttribute, created) => {
    if(created){
        doSomethingWith(userAttribute.user);
    }
    else{...}
});

Note that you can access the property "user" of userAttribute now.

If the userAttribute object is created (not found), you should of course create the user object as well.

Edit: By the way, you must relate userAttribute to user as well, if you have not already done so, via

userAttribute.belongsTo(User);
Comments