Skip to content

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

Open
@alekbarszczewski

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions