在续集中使用groupby来获得一组分组项

时间:2019-03-21 05:17:52

标签: mysql sqlite express sequelize.js

我正在使用sequelize(4.42.0)和express。我有两个表categoriesmain_categories,它们具有以下关联:

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

我尝试使用以下sequelize命令获取归类在其主要类别下的所有类别的列表:

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

上述序列化代码的输出为:

{
    "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": []
        }
    ]
}

对我来说,预期的输出是每个main_category中的categorys数组将包含属于同一主要类别的所有类别的详细信息,而不仅仅是上面输出中所示的一个。

我的main_categories数据表: enter image description here

我的categories数据表: enter image description here

1 个答案:

答案 0 :(得分:0)

因此,我后来发现,由于已经声明了关联,因此我们只需要包含没有任何groupby子句的模型即可。所以对我有用的最终代码是:

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