Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Postgres: Sequelize Group, isn't working when referencing the include table column

This is my code,
I really don’t know how to fix this issue anymore

when I enter this code.

     db.models.Price.findAll({
        attributes:['id', 'item.item_name'],
        group: [
            ['masterfile_price.id','item.id','item.item_name']
        ],
        // [sequelize.literal('Item.item_name')]
        //  ['masterfile_price.id']

        raw: true,
        include: [{
            model: db.models.Item,
            as: 'item',
            attributes: ['id',"item_name"],
        }],

    })
        

It will give me this error
error DatabaseError [SequelizeDatabaseError]: column "item.item_name" must appear in the GROUP BY clause or be used in an aggregate function
I don’t know why

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the query is this

SELECT
"masterfile_price"."id",
"item"."item_name",
"item"."id" AS "item.id",
"item"."item_name" AS "item.item_name" 
FROM
"masterfile_prices" AS "masterfile_price"
LEFT OUTER JOIN "masterfile_items" AS "item" ON "masterfile_price"."itemId" = "item"."id" 
GROUP BY
"masterfile_price"."id";
    

the problem is
I only want the item_name

in my orignal query without using sequelize
it’s working this

    SELECT
    "item"."item_name" AS "item.item_name" 
    FROM
    "masterfile_prices" AS "masterfile_price"
    LEFT OUTER JOIN "masterfile_items" AS "item" ON "masterfile_price"."itemId" = "item"."id" 
    GROUP BY
    item.item_name;

which will the results of

item.item_name
test9
test10

I don’t know why I can’t replicate it, in sequelize,
or am I missing something?

or is there something wrong with sequelize group by

>Solution :

group option should be either string | Fn | Col or an array of string | Fn | Col. So you need to remove extra brackets:

group: ['masterfile_price.id','item.id','item.item_name']

If you want to select and group by only item.item_name then you need to indicate only it in both attributes and group options:

db.models.Price.findAll({
        attributes:[[Sequelize.col('item.item_name'), 'item_name']],
        group: Sequelize.col('item.item_name'),
        raw: true,
        include: [{
            model: db.models.Item,
            as: 'item',
            attributes: [],
        }],
    })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading