question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Sequelize : Get Subquery/Raw Query as model for include

See original GitHub issue

I have gone through the Sequelize doc, but can’t find anything helpful

What I want to do is to add raw query or custom model in include, is it possible ?

model.Post.findAll({
            include: [{
                    model: model.User,
                    attributes: ['fullname', 'profilepic'],
                },
                {
                    model: model.PostComments,
                },
                {
                    model: "Raw Query"
                }
            ]
        }

What I want to achieve is like :

Select post_id, count(*) as total_likes from post_likes group by post_id

I can’t achieve this by using simply include, so what I want to do is create a table/model from above query and then use it inside include.

If I use group by withing include it gives group by from top level, and I want to apply group by just for the post_like table.

Please let me know, if it found confusing or not clear.

Dialect: postgres

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
harpciocommented, Sep 19, 2019

I have a lot of problems with PostreSQL vs MySQL compatibility. This is working for both.

let ordersCountSQL = sequelize.dialect.QueryGenerator.selectQuery('orders', {
    attributes: [
        [sequelize.fn('COUNT', sequelize.col('orders.id')), 'orders_count']
    ],
    where: {
        customer_id: {
            [Op.eq]: sequelize.col('Customer.id')
        }
    }
}).slice(0, -1);

let totalPurchaseSQL = sequelize.dialect.QueryGenerator.selectQuery('orders', {
    attributes: [
        [sequelize.fn('SUM', sequelize.col('orders.total')), 'total_purchase']
    ],
    where: {
        customer_id: {
            [Op.eq]: sequelize.col('Customer.id')
        }
    }
}).slice(0, -1);

const customers = await Customer.findAndCountAll({
    attributes: {
        include: [
            [sequelize.literal('(' + ordersCountSQL + ')'), 'orders_count'],
            [sequelize.literal('(' + totalPurchaseSQL + ')'), 'total_purchase'],
        ],
    },
    include: [
        {
            association: 'orders',
            model: Order,
            attributes: [],
        },
    ],
    subQuery: false,
    group: ['Customer.id']
});
2reactions
sushantdhimancommented, Dec 5, 2017

Please follow the issue template

Read more comments on GitHub >

github_iconTop Results From Across the Web

Sequelize : Get Subquery/Raw Query as model for include
I was looking to do the same, use a raw query dynamically formed inside the include but there's no possible way to use...
Read more >
Raw Queries - Sequelize
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can use...
Read more >
Writing RAW SQL Queries in Sequelize for Express JS.
If you look at the first snippet, the dynamic values in the raw query are wrapped in () and the key is set...
Read more >
How to execute/ use a raw query with Sequelize
Sequelize raw query options ... The query() method of the Sequelize instance also allows you to pass an object containing pre-defined options ....
Read more >
Raw queries - Manual | Sequelize
As there are often use cases in which it is just easier to execute raw / already prepared SQL queries, you can utilize...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found