Skip to content

How to parse model and associations from raw query? #790

Open

Description

@alekbarszczewski

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?

For now posts[0].dataValues looks like this:

{      id: 1,
       type: 'video',
       isPublished: true,
       publishedAt: Wed Jan 01 2014 01:00:00 GMT+0100 (CET),
       thumbnailUrl: 'http://placehold.it/230x150&text=post1',
       isFeatured: false,
       isDailyContent: false,
       lovesCount: 0,
       commentsCount: 0,
       CategoryId: 1,
       SeriesId: 1,
       UserId: 4,
       AuthorId: null,
       createdAt: Wed May 28 2014 18:07:28 GMT+0200 (CEST),
       updatedAt: Wed May 28 2014 18:07:28 GMT+0200 (CEST),
       'PostTranslations.id': 2,
       'PostTranslations.language': 'zh-cn',
       'PostTranslations.PostId': 6 }

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

Activity

  1. mickhansen commented on May 29, 2014

    @mickhansen

    You'll have to provide include options and make sure they are valided aswell.

    Something like this might work:

    var options = {
      include: etc
    };
    Sequelize.Model.validateIncludedElements(options);
    sequelize.query(q,Post, options).done(function(err,posts){
        console.error(posts[0])
    })
  2. mickhansen commented on May 29, 2014

    @mickhansen

    Not sure this will work though, you'll have to fiddle around with it.

  3. alekbarszczewski commented on May 29, 2014

    @alekbarszczewski
    Author

    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...

  4. mickhansen commented on May 29, 2014

    @mickhansen

    Are you using master?
    I just realized it's only exposed as Sequelize.Model.$validateIncludedElements on the current master.

  5. alekbarszczewski commented on May 29, 2014

    @alekbarszczewski
    Author

    I am using sequelize 1.7.5. Is it possible to make it work on this version?

  6. mickhansen commented on May 29, 2014

    @mickhansen

    Most likely not, not without modifying your local copy of sequelize.

  7. alekbarszczewski commented on May 29, 2014

    @alekbarszczewski
    Author

    Damn so I stucked :(. I guess its high time I switched to master...

  8. mickhansen commented on May 29, 2014

    @mickhansen

    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.

  9. alekbarszczewski commented on May 29, 2014

    @alekbarszczewski
    Author

    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...

  10. mickhansen commented on May 29, 2014

    @mickhansen

    dev11 is not master :)
    To install master you should npm install --save sequelize/sequelize

  11. alekbarszczewski commented on May 29, 2014

    @alekbarszczewski
    Author

    Thanks, I managed to install master.
    Hovever I still can't make it work according to my issue:

    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")"
    ';
    
    options = { include: [{ model: PostTranslation }] }
    
    Sequelize.Model.$validateIncludedElements.call(Post,options);
    
    sequelize.query(q,Post,options).done(function(err,posts){
        console.error(posts[0])
    })
    

    Result is same as I wrote before - PostTranslations is not parsed from the query result and still:

    {      id: 1,
           type: 'video',
           isPublished: true,
           publishedAt: Wed Jan 01 2014 01:00:00 GMT+0100 (CET),
           thumbnailUrl: 'http://placehold.it/230x150&text=post1',
           isFeatured: false,
           isDailyContent: false,
           lovesCount: 0,
           commentsCount: 0,
           CategoryId: 1,
           SeriesId: 1,
           UserId: 4,
           AuthorId: null,
           createdAt: Wed May 28 2014 18:07:28 GMT+0200 (CEST),
           updatedAt: Wed May 28 2014 18:07:28 GMT+0200 (CEST),
           'PostTranslations.id': 2,
           'PostTranslations.language': 'zh-cn',
           'PostTranslations.PostId': 6 }
    
  12. mickhansen commented on May 29, 2014

    @mickhansen

    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.

  13. alekbarszczewski commented on May 29, 2014

    @alekbarszczewski
    Author

    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...

  14. alekbarszczewski commented on May 29, 2014

    @alekbarszczewski
    Author

    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:

    Post.hasMany(PostTranslation)
    PostTranslation.belongsTo(Post)
    ...
    Post.findAll({ include: [{ model: PostTranslation }] }).done (err, posts) ->
       throw err if err
       res.json { items: posts }
    

    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)
    
  15. alekbarszczewski commented on May 29, 2014

    @alekbarszczewski
    Author

    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?

    {
      "items": [
        {
          "Posts": {
            "id": 1
          },
          "PostTranslations": {
            "id": 2,
            "language": "zh-cn",
            "PostId": 1
          }
        },
        {
          "Posts.id": 1,
          "PostTranslations.id": 1,
          "PostTranslations.language": "en-us",
          "PostTranslations.PostId": 1
        },
        {
          "Posts.id": 2,
          "PostTranslations.id": 3,
          "PostTranslations.language": "en-us",
          "PostTranslations.PostId": 2
        },
        {
          "Posts.id": 3,
          "PostTranslations.id": 4,
          "PostTranslations.language": "zh-cn",
          "PostTranslations.PostId": 3
        },
        {
          "Posts.id": 4,
          "PostTranslations.id": 5,
          "PostTranslations.language": "en-us",
          "PostTranslations.PostId": 4
        },
        {
          "Posts.id": 5,
          "PostTranslations.id": 6,
          "PostTranslations.language": "en-us",
          "PostTranslations.PostId": 5
        },
        {
          "Posts.id": 6,
          "PostTranslations.id": 7,
          "PostTranslations.language": "en-us",
          "PostTranslations.PostId": 6
        }
      ]
    }
    
  16. 30 remaining items

  17. LeoDoldan7 commented on Apr 23, 2019

    @LeoDoldan7

    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.

  18. jelnur commented on May 16, 2019

    @jelnur

    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 }
    )

  19. ds11yadav commented on Nov 18, 2019

    @ds11yadav

    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 ??

  20. eshton commented on Nov 29, 2019

    @eshton

    Hi, none of the above works for me. Is there any update on this? Thanks.

  21. reopened this on Jan 16, 2020
  22. self-assigned this
    on Jan 16, 2020
  23. jy95 commented on Jan 17, 2020

    @jy95

    @papb I think a compromise for that could be to allow scopes for that kind of things

    For example :

    const query = `Some query compliant with Sequelize dot type`;
    
    let exerciseScope = [
        "default_attributes_for_bulk",
        "with_exercise_metrics",
        "with_related_tags_with_their_category"
    ];
    
    let options = {
       hasJoin: true,
       mapToModel: true,
       model: models.Exercise.scope(exerciseScope),
       type: models.sequelize.QueryTypes.SELECT,
    };
    
    const returnObjs = await models.sequelize.query(query, options);

    instead of

    let subOptions = models.Exercise.scope(exerciseScope)._scope;
    let options = Object.assign(subOptions, { hasJoin: true, };
    models.Exercise._validateIncludedElements(subOptions);
    const returnObjs = await models.sequelize.query(query, options);

    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 ...

  24. nicoabie commented on Jan 21, 2022

    @nicoabie

    Here there is a solution for Sequelize 6.9.0

    const jsonObjects = await sequelize.query(catalyticConvertersRawQuery(), {
      nest: true,
      type: QueryTypes.SELECT,
    });
    
    const rows = jsonObjects.map((row) => CatalyticConverter.build(row, { include }));
  25. nicoabie commented on Jan 21, 2022

    @nicoabie

    @papb I think you can close this issue and update the documentation.
    It appears mapToModel and model attributes in query options do nothing.

  26. tonypee commented on Feb 15, 2022

    @tonypee

    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

  27. nicoabie commented on Feb 17, 2022

    @nicoabie

    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

    #790

  28. thadeu commented on Dec 8, 2022

    @thadeu
  29. d00rsfan commented on Mar 10, 2023

    @d00rsfan
    const rows = 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.

  30. transferred this issue fromsequelize/sequelizeon Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions