简体   繁体   中英

Sequelize where query of a one to many association attribute?

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?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM