expressrest和sequelize-complex嵌套查询需要建议吗

cwtwac6a  于 2021-06-19  发布在  Mysql
关注(0)|答案(0)|浏览(147)

我刚开始续集,在一个项目中,我有三个模型:

Project({name: String}), 
Task({name: String}),
TaskCategory({name: String})

Project.hasMany(Task)
Task.belongsTo(TaskCategory)

我需要创建一个返回如下内容的查询:
get/api/projects/:id

{
  "id": "1",
  "name": "Project 1",
  "tasks": [
    {
      "id": "1",
      "name": "task 1",
      "category": {
        "id": "1",
        "name": "category 1"
      }
    },
    {
      "id": "2",
      "name": "task 2",
      "category": {
        "id": "2",
        "name": "category 1"
      }
    }
  ],
  "taskCount": "2",
  "taskCountPerCategory": [
    {
      "id": "1",
      "category": {
        "id": "1",
        "name": "category 1"
      },
      "count": "2"
    },
    {
      "id": "2",
      "category": {
        "id": "2",
        "name": "category 2"
      },
      "count": "0"
    },
    {
      "id": "3",
      "category": {
        "id": "3",
        "name": "category 3"
      },
      "count": "0"
    },
    {
      "id": "4",
      "category": {
        "id": "4",
        "name": "category 4"
      },
      "count": "0"
    }
  ]
}

我真的被这个困住了。我知道我可以这样做:

Project.find({
    where: {id: 1}, 
    include: [{model: Task, include: [{model: TaskCategory}]}]
})

但我对“taskcount”,“taskcountpercategory”的部分迷茫了。
请注意,“taskcountpercategory”应检索系统中每个taskcategory的任务计数。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题