Skip to content

Instantly share code, notes, and snippets.

@malikid
Created November 22, 2017 18:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malikid/92bd870638d020ef857f12ba485020c5 to your computer and use it in GitHub Desktop.
Save malikid/92bd870638d020ef857f12ba485020c5 to your computer and use it in GitHub Desktop.
Notes for ORM Sequelize - findOne/findAll while joining more than two tables
/*************************************************
* findAll VS findOne (Wrong!!! Not as expected) *
*************************************************/
// findAll - Sequelize Code
test = (guideId) => this.Manual.findAll({
include: [
{model: this.Topic, required: true, include: [
{model: this.Guide, where: {id: guideId}}
]}
]
});
// findAll - Interpreted SQL (Modified for being readable)
SELECT "manual".*, "topics".*, "topics->guides".*
FROM "test"."manuals" AS "manual"
INNER JOIN "test"."topics" AS "topics" ON "manual"."id" = "topics"."manual_id"
INNER JOIN "test"."guides" AS "topics->guides" ON "topics"."id" = "topics->guides"."topic_id" AND "topics->guides"."id" = '37abff8e-003f-431a-8712-fe61c03f31f3';
// findOne - Sequelize Code
test = (guideId) => this.Manual.findOne({
include: [
{model: this.Topic, required: true, include: [
{model: this.Guide, where: {id: guideId}}
]}
]
});
// findOne - Interpreted SQL (Modified for being readable)
SELECT "manual".*, "topics".*, "topics->guides".*
FROM (
SELECT "manual".*
FROM "test"."manuals" AS "manual"
WHERE (
SELECT "manual_id"
FROM "test"."topics" AS "topics"
WHERE ("topics"."manual_id" = "manual"."id")
LIMIT 1
) IS NOT NULL
LIMIT 1
) AS "manual"
INNER JOIN "test"."topics" AS "topics" ON "manual"."id" = "topics"."manual_id"
INNER JOIN "test"."guides" AS "topics->guides" ON "topics"."id" = "topics->guides"."topic_id" AND "topics->guides"."id" = '1d479161-57b6-4b30-92ef-601c026f5d55';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment