Eager loading: select all rows without association in mn-table
See original GitHub issueAgain, the eager loading is bugging me and I can’t figure how to achieve a select which selects all rows from given table, which do NOT join on a second model.
In pure SQL, I’d write my query like this:
SELECT column1 from Parameters LEFT OUTER JOIN ParameterProjects ON (Project.id = ParameterProjects.parameter_id) WHERE ParameterProjects.parameter_id IS NULL;
It’s usually a quite trivial task to fetch all rows which are not (yet) linked to table#2 (Projects). In sequelize however I the only way I know to get the mn-table involved is to include the associated model. My first idea was to use Sequelize.or() (which is technically working now, thanks Mick!) and query for Sequelize.or({project_id: 1},{project_id:null})
, but I didn’t pay enough attention at the generated query.
It looks like this:
SELECT `Parameters` . * , `Projects`.`id` AS `Projects.id` , `Projects`.`name` AS `Projects.name` , `Projects`.`url` AS `Projects.url` , `Projects`.`api_key` AS `Projects.api_key` , `Projects`.`created_at` AS `Projects.created_at` , `Projects`.`customer_id` AS `Projects.customer_id` , `Projects.ParametersProject`.`project_id` AS `Projects.ParametersProject.project_id` , `Projects.ParametersProject`.`parameter_id` AS `Projects.ParametersProject.parameter_id`
FROM `Parameters`
INNER JOIN `ParametersProjects` AS `Projects.ParametersProject` ON `Parameters`.`id` = `Projects.ParametersProject`.`parameter_id`
INNER JOIN `Projects` AS `Projects` ON `Projects`.`id` = `Projects.ParametersProject`.`project_id`
AND (
`Projects`.`id` = '1'
OR `Projects`.`id` IS NULL
)
WHERE (
`Parameters`.`key` = 'cpu'
)
Table Parameters joins ParameterProjects on the Project.id, ParameterProjects joins Projects. Those are INNER JOINS and as far as I understand SQL (please correct if I’m wrong) Projects.ParametersProject
.parameter_id
can never be NULL.
Is there perhaps another way to achieve this?
Oh, and btw: Where are the fancy subselects gone? I could swear the last time I tried to solve my issue the queries had subselects in it.
Issue Analytics
- State:
- Created 10 years ago
- Comments:13 (4 by maintainers)
I’m also interested how can this be solved in version 4. Using required:false returns all rows (with and without having association).
@YouriT You should be able to use
where: { '$portfolios.userId$': null },
to avoid prepending the parent name as well