You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
How to parse model and associations from raw query? #790
From time to time I have to write very complex query that cannot be handled by Sequelize default methods. So I write raw query by hand and I execute it using sequelize instance and passing also sequelize model:
Post.hasMany(PostTranslation);
q = '
SELECT
"Posts".*,
"PostTranslations"."id" AS "PostTranslations.id",
"PostTranslations"."language" AS "PostTranslations.language",
"PostTranslations"."PostId" AS "PostTranslations.PostId"
FROM "Posts"
INNER JOIN "PostTranslations" AS "PostTranslations"
ON ("Posts"."id" = "PostTranslations"."PostId")"
';
sequelize.query(q,Post).done(function(err,posts){
console.error(posts[0])
})
That partialy works as I get array of post models however Sequelize does not detect that there are any associated models included... Is there any way to "inform" Sequelize how to parse selected rows to build models with their associations?
As you can see all columns are treated as Post model properties instead of PostTranslation properties. Am I doing something wrong?
Using Sequelize 1.7.5
Reacted by junho, Daniel Kolesnik and Edmundo Santos
Hmm I can't figure out how to access validateIncludedElements. Sequelize.Model is function that does not have this method... I couldnt find this method in any of available objects: Post, sequelize (instance), Sequelize, Sequelize.Model - also tried $validateIncludedElements (I found it in src) but I couldnt find it either...
Hmm I have problem with installing latest (unstable) version of sequelize...
I tried npm install --save sequelize@unstable - it installed sequelize with correct package.json (with version 2.0.0-dev11) however with invalid (old) source code - ie. there is lib/dao.js instead of lib/model.js -> this is weird...
You might need to validate options and then pass them to query like it's done here.
Although looking at the params it should work with what you have right now.
Hmm, for now I cant make it work :(. I looked up queryOptions that are passed when normal Post.findAll is executed and it's pretty much the same as queryOptions after $validate...
I am trying still trying to make it work. For now I get strange error which appears only on 2.0.0-dev11 and master and it works fine on 1.7.5 - For the following code:
Code above generates following error - any ideas what might be wrong? I guess this is because sequelize 2.0.0 + is not backward compatibile but I can't figure out whats wrong...
Possibly unhandled TypeError: Cannot set property postTranslations of [object Object] which has only a getter
at [object Object].module.exports.Instance._setInclude (/Users/alek/Desktop/wl/node_modules/sequelize/lib/instance.js:394:24)
at [object Object].module.exports.Instance.set (/Users/alek/Desktop/wl/node_modules/sequelize/lib/instance.js:279:16)
at [object Object].module.exports.Instance.set (/Users/alek/Desktop/wl/node_modules/sequelize/lib/instance.js:251:20)
at [object Object].module.exports.initValues (/Users/alek/Desktop/wl/node_modules/sequelize/lib/instance.js:896:10)
at [object Object].module.exports.Instance (/Users/alek/Desktop/wl/node_modules/sequelize/lib/instance.js:52:16)
at new Instance.DAO (/Users/alek/Desktop/wl/node_modules/sequelize/lib/model.js:235:16)
at [object Object].module.exports.Model.build (/Users/alek/Desktop/wl/node_modules/sequelize/lib/model.js:954:12)
at [object Object].<anonymous> (/Users/alek/Desktop/wl/node_modules/sequelize/lib/model.js:972:19)
at Array.map (native)
at [object Object].module.exports.Model.bulkBuild (/Users/alek/Desktop/wl/node_modules/sequelize/lib/model.js:971:22)
at [object Object].module.exports.handleSelectQuery (/Users/alek/Desktop/wl/node_modules/sequelize/lib/dialects/abstract/query.js:244:28)
at [object Object].module.exports.AbstractQuery.send (/Users/alek/Desktop/wl/node_modules/sequelize/lib/dialects/abstract/query.js:117:26)
at /Users/alek/Desktop/wl/node_modules/sequelize/lib/dialects/postgres/query.js:140:23
at tryCatchApply (/Users/alek/Desktop/wl/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/util.js:83:19)
at Promise$_callSpread [as _callSpread] (/Users/alek/Desktop/wl/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:709:12)
at Promise$_callHandler [as _callHandler] (/Users/alek/Desktop/wl/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:717:18)
at Promise$_settlePromiseFromHandler [as _settlePromiseFromHandler] (/Users/alek/Desktop/wl/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:737:18)
at Promise$_settlePromiseAt [as _settlePromiseAt] (/Users/alek/Desktop/wl/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:899:14)
at Promise$_settlePromises [as _settlePromises] (/Users/alek/Desktop/wl/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/promise.js:1037:14)
at Promise.b (domain.js:183:18)
at Async$_consumeFunctionBuffer [as _consumeFunctionBuffer] (/Users/alek/Desktop/wl/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/async.js:74:12)
at Async$consumeFunctionBuffer (/Users/alek/Desktop/wl/node_modules/sequelize/node_modules/sequelize-bluebird/js/main/async.js:37:14)
I solved the unhandledException error - it was caused because I manually set up getter called postTranslations...
Anyway I gave up trying to force Sequelize to parse results correctly - it seems that many "things" happen in Model.findAll including calls to functions that are not exported by the module (so it's not possible to reach them outside sequelize source)...
I thought about parsing results myself and tried sequelize.query(q,null,{ raw: true }).done(..) - unfortunately sequelize returns very strange result - first row is parsed correctly and others not... whats going on?
I think it is REALLY important to mention that the order of the attributes is important for Sequelize to parse it. I only make it work respecting the depth levels.
SELECT
grandparent.name AS "name",
grandparent.lastname AS "lastname",
parent.name AS "parent.name",
first_child.name AS "parent.firstChild.name",
first_child.lastname AS "parent.firstChild.lastname",
second_child.name AS "parent.secondChild.name",
second_child.lastname AS "parent.secondChild.lastname",
Works perfectly.
BUT THIS:
SELECT
grandparent.name AS "name",
first_child.name AS "parent.firstChild.name",
second_child.lastname AS "parent.secondChild.lastname",
grandparent.lastname AS "lastname",
parent.name AS "parent.name",
first_child.lastname AS "parent.firstChild.lastname",
second_child.name AS "parent.secondChild.name",
Does not return some attributes. It may be obvious for most of you I think, but I was struggling with it for a while. Order matters.
Here's what worked for me: sequelize.query( SELECT q.id, q.title, a.id AS "answers.id" FROM questions q JOIN answers a ON a.question_id = q.id, model: Question, mapToModel: true, nest: true, raw: true, type: sequelize.QueryTypes.SELECT } )
Reacted by Reijo Sirila, ericxinzhang, da-derekliang, Vo Trong Ky Dinh, iamsimakov, Shem, Oseias Silva, Serhiy Balan, Vyacheslav Anisimov, Tbuglc and 2 more
Here's what worked for me: sequelize.query( SELECT q.id, q.title, a.id AS "answers.id" FROM questions q JOIN answers a ON a.question_id = q.id, model: Question, mapToModel: true, nest: true, raw: true, type: sequelize.QueryTypes.SELECT } )
what if there there is jOIN between two table and need to map model on both the table ??
I tested on my models and only the version with _scope works. I was expecting that if a model with scope(s) was provided, it should internal use _validateIncludedElements instead of rely on explicit setting that ...
constjsonObjects=awaitsequelize.query(catalyticConvertersRawQuery(),{nest: true,type: QueryTypes.SELECT,});constrows=jsonObjects.map((row)=>CatalyticConverter.build(row,{ include }));
Reacted by Danil Valov, Ibe Agwu and Edmundo Santos
DId anyone ever find how to do this? It seems a pretty core feature when using custom queries. It would be great if the documentation could show an example of nested models being parsed
DId anyone ever find how to do this? It seems a pretty core feature when using custom queries. It would be great if the documentation could show an example of nested models being parsed
constrows=jsonObjects.map((row)=>CatalyticConverter.build(row,{ include }));
Thanks, BTW
there is sideeffect: it call setter and after getter (in my case I use JSON stringify/parse - so first it wrap string with quotes, and after parse quoted string and get instance with string in attribute instead of object) - made workaround - do not stringify if it's already string.
Activity
mickhansen commentedon May 29, 2014
You'll have to provide include options and make sure they are valided aswell.
Something like this might work:
mickhansen commentedon May 29, 2014
Not sure this will work though, you'll have to fiddle around with it.
alekbarszczewski commentedon May 29, 2014
Hmm I can't figure out how to access
validateIncludedElements. Sequelize.Model is function that does not have this method... I couldnt find this method in any of available objects: Post, sequelize (instance), Sequelize, Sequelize.Model - also tried$validateIncludedElements(I found it in src) but I couldnt find it either...mickhansen commentedon May 29, 2014
Are you using master?
I just realized it's only exposed as Sequelize.Model.$validateIncludedElements on the current master.
alekbarszczewski commentedon May 29, 2014
I am using sequelize 1.7.5. Is it possible to make it work on this version?
mickhansen commentedon May 29, 2014
Most likely not, not without modifying your local copy of sequelize.
alekbarszczewski commentedon May 29, 2014
Damn so I stucked :(. I guess its high time I switched to master...
mickhansen commentedon May 29, 2014
Yeah unfortuneatly so, unless you want to fork 1.7.6 and provide the small change for your local development untill your ready to switch to master.
alekbarszczewski commentedon May 29, 2014
Hmm I have problem with installing latest (unstable) version of sequelize...
I tried
npm install --save sequelize@unstable- it installed sequelize with correctpackage.json(with version2.0.0-dev11) however with invalid (old) source code - ie. there islib/dao.jsinstead oflib/model.js-> this is weird...mickhansen commentedon May 29, 2014
dev11 is not master :)
To install master you should npm install --save sequelize/sequelize
alekbarszczewski commentedon May 29, 2014
Thanks, I managed to install master.
Hovever I still can't make it work according to my issue:
Result is same as I wrote before -
PostTranslationsis not parsed from the query result and still:mickhansen commentedon May 29, 2014
Yeah it appears it's a bit more advanced than that, take a look at: https://github.com/sequelize/sequelize/blob/master/lib/query-interface.js#L538
You might need to validate options and then pass them to query like it's done here.
Although looking at the params it should work with what you have right now.
alekbarszczewski commentedon May 29, 2014
Hmm, for now I cant make it work :(. I looked up queryOptions that are passed when normal Post.findAll is executed and it's pretty much the same as queryOptions after $validate...
alekbarszczewski commentedon May 29, 2014
I am trying still trying to make it work. For now I get strange error which appears only on
2.0.0-dev11andmasterand it works fine on1.7.5- For the following code:Code above generates following error - any ideas what might be wrong? I guess this is because sequelize 2.0.0 + is not backward compatibile but I can't figure out whats wrong...
alekbarszczewski commentedon May 29, 2014
I solved the unhandledException error - it was caused because I manually set up getter called
postTranslations...Anyway I gave up trying to force Sequelize to parse results correctly - it seems that many "things" happen in
Model.findAllincluding calls to functions that are not exported by the module (so it's not possible to reach them outside sequelize source)...I thought about parsing results myself and tried
sequelize.query(q,null,{ raw: true }).done(..)- unfortunately sequelize returns very strange result - first row is parsed correctly and others not... whats going on?30 remaining items
LeoDoldan7 commentedon Apr 23, 2019
I think it is REALLY important to mention that the order of the attributes is important for Sequelize to parse it. I only make it work respecting the depth levels.
Works perfectly.
BUT THIS:
Does not return some attributes. It may be obvious for most of you I think, but I was struggling with it for a while. Order matters.
jelnur commentedon May 16, 2019
Here's what worked for me:
sequelize.query(SELECT q.id, q.title, a.id AS "answers.id"FROM questions qJOIN answers a ON a.question_id = q.id,model: Question,mapToModel: true,nest: true,raw: true,type: sequelize.QueryTypes.SELECT })ds11yadav commentedon Nov 18, 2019
what if there there is jOIN between two table and need to map model on both the table ??
eshton commentedon Nov 29, 2019
Hi, none of the above works for me. Is there any update on this? Thanks.
jy95 commentedon Jan 17, 2020
@papb I think a compromise for that could be to allow scopes for that kind of things
For example :
instead of
I tested on my models and only the version with _scope works. I was expecting that if a model with scope(s) was provided, it should internal use
_validateIncludedElementsinstead of rely on explicit setting that ...nicoabie commentedon Jan 21, 2022
Here there is a solution for Sequelize 6.9.0
nicoabie commentedon Jan 21, 2022
@papb I think you can close this issue and update the documentation.
It appears
mapToModelandmodelattributes in query options do nothing.tonypee commentedon Feb 15, 2022
DId anyone ever find how to do this? It seems a pretty core feature when using custom queries. It would be great if the documentation could show an example of nested models being parsed
nicoabie commentedon Feb 17, 2022
#790
thadeu commentedon Dec 8, 2022
d00rsfan commentedon Mar 10, 2023
Thanks, BTW
there is sideeffect: it call setter and after getter (in my case I use JSON stringify/parse - so first it wrap string with quotes, and after parse quoted string and get instance with string in attribute instead of object) - made workaround - do not stringify if it's already string.