Atul Stha
Atul Stha

Reputation: 1524

Using groupby in sequelize to get an array of the grouped items

I am using sequelize(4.42.0) along with express. I have two tables categories and main_categories which has the following association:

db.main_categories.hasMany(db.categories);
db.categories.belongsTo(db.main_categories);

I tried to get list of all the categories grouped under their main category using following sequelize command:

      var _categoryList = await models.main_categories.findAll({include: [{model: models.categories}], group:['main_categories.id']});
 res.send({category_list: _categoryList});

The output of the above sequelize code is :

{
    "category_list": [
        {
            "id": 1,
            "name": "Physics",
            "created_at": null,
            "updated_at": null,
            "categories": [
                {
                    "id": 1,
                    "name": "Mechanics",
                    "created_at": "2019-03-21T03:39:48.000Z",
                    "updated_at": "2019-03-21T03:39:48.000Z",
                    "main_category_id": 1
                }
            ]
        },
        {
            "id": 2,
            "name": "Chemistry",
            "created_at": null,
            "updated_at": null,
            "categories": [
                {
                    "id": 6,
                    "name": "General and Physical Chemistry",
                    "created_at": "2019-03-21T03:42:54.000Z",
                    "updated_at": "2019-03-21T03:42:54.000Z",
                    "main_category_id": 2
                }
            ]
        },
        {
            "id": 3,
            "name": "Zoology",
            "created_at": null,
            "updated_at": null,
            "categories": []
        },
        {
            "id": 4,
            "name": "Botany",
            "created_at": null,
            "updated_at": null,
            "categories": []
        }
    ]
}

The expected output for me was that the categories array inside each main_category would contain details of all the categories falling under the same main category instead of just one as shown in the output above.

My main_categories table with data: enter image description here

my categories table with data: enter image description here

Upvotes: 0

Views: 1834

Answers (1)

Atul Stha
Atul Stha

Reputation: 1524

So I later found out that as the associations had already been declared we just need to include the model without any groupby clause. So the final code that worked for me was :

var _categoryList = await models.main_categories.findAll({include: [{model: models.categories}]});

Upvotes: 2

Related Questions