Sequelize where query of a one to many association attribute?

Niall McKenna :

I have the following tables in a database:

Users: id|name|age Hobbies: id|user_id|hobby

In sequelize I have the following associations:

Users.hasMany(Hobbies) Hobbies.belongTo(Users)

To retrieve a list of users along with their hobbies the query is as follows:

Users.findAll(include: [{model: Hobbies}])

I map the result of the query to a domain object.

The result of the query looks something like this:

[{id: 1, name: 'John', age: 20, hobbies: ['fishing', 'running']}]

I am trying to return a list of users that have a hobby of fishing.

As I understand it I can apply a where query on the association itself like this:

Users.findAll(include: [{model: Hobbies, where: {hobby: 'fishing'}}])

but this will still return all users, and will only return the hobbies for each user that are fishing.

Is there a way to apply a where query at the user level based on their hobbies?

Soham Lawar :

I think you need to change the join type. Sequelize by default uses left outer join while joining two models but if you change that to inner join by setting required to true you will get intended results -

Users.findAll(include: [{model: Hobbies, where: {hobby: 'fishing'}, required : true}])

I hope it helps!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=217404&siteId=1