简体   繁体   English

Sequelize where 查询一对多关联属性?

[英]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:据我了解,我可以像这样对关联本身应用 where 查询:

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?有没有办法根据用户的爱好在用户级别应用 where 查询?

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 - Sequelize 在连接两个模型时默认使用左外连接,但如果您通过将required设置为true将其更改为内连接,您将获得预期的结果 -

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

I hope it helps!我希望它有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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