Himmators Himmators - 1 year ago 80
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) => {

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 Source

You can easily use eager loading for that.

    where: {'name': 'fbprofile', 'value': profile.id },
    include: [ User ]
.spread((userAttribute, created) => {

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

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