NodeJS Sequelize and FindAll with Include and constraints

怎甘沉沦 提交于 2019-12-05 05:23:04

问题


I am trying to use the Include capabilities in the Find all to Eager load the data i need in a single query. My issue is that all the includes are LEFT OUTER JOIN ... which is good but i am not seeing a way to add additional constraints to that LEFT OUTER JOIN.

My query would look something like:

Matches.findAll(
   {where: ["match.isPublished = ?", true], 
    include: [RoundMaps, 
              Locations, 
              {model: MemberMaps, as: "MemberMaps", where: ["memberMaps.memberUUID = ?", authenticatedUser.uuid]}]})

But this does not seem to be supported ... at least the way i have the syntax written. I cannot add that constraint to the constraints on the LEFT OUTER JOIN ... adding the same constraint to the WHERE clause does not work ... as that gives me only the Matches that the Member is associated with. I want the list of all public Matches and to know which of those that the member has already established an association.

Can it be done? Sequelize seems to be getting most things done! But still struggling with some things.

Insights welcome!

Cheers


回答1:


According to your question this is not possible using where clause with LEFT OUTER JOIN. For this you have to write SQL queries to list of all public Matches and to know which of those that the member has already established an association.

sequelize.query('SELECT * FROM "Matches" LEFT OUTER JOIN "RoundMaps" ON "Matches".id = "RoundMaps".match_id LEFT OUTER JOIN "Locations" ON "Matches".id = "Locations".match_id    LEFT OUTER JOIN (SELECT * FROM "MemberMaps" WHERE "MemberMaps".memberUUID = ?) AS "MemberMaps" ON "Matches".id = "MemberMaps".match_id WHERE "Matches".isPublished = ?', null, { raw: true }, [memberUUID,true ]).success(function(myTableRows) {
console.log(myTableRows);
res.send(myTableRows);
});

Executing raw SQL queries in Sequelize




回答2:


There is an option on INCLUDE that specifies whether the join will be inner or outer: include.require = boolean

When there isn't a where: clause specified, then it defaults to false. But, it gets set to true when a where: is set.

You can explicitly turn that off to fetch all of the results of the findAll().

Unfortunately, the only examples I've seen of this are in the codebase itself, but here it is: sequelize/test/integration/associations/belongs-to-many.test.js#L167



来源:https://stackoverflow.com/questions/19050248/nodejs-sequelize-and-findall-with-include-and-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!