knex:如何从结果创建对象?

时间:2018-10-26 05:31:27

标签: mysql node.js knex.js

MySQL版本:5.7.23 knex.js版本:0.15.2

现在我有3个表可以互相连接

table: projects
  - id (pk)
  - project_name
  - project_detail

table: user_projects
  - project_id (pk, fk from projects)
  - user_id (pk, fk from users)
  - success_percent

table: project_todos
  - id (pk)
  - project_id (fk from projects)
  - user_id (fk from users)
  - todo_detail
  - status
  - will_finish_date

我想加入3个表,然后结果是

{
      project_name: "lorem ipsum",
      project_detail: "",
      success_percent: 50,
      todos: [
         {
           id: 1,
           todo_detail: "sleep",
           status: 0,
           will_finish_date: 2018-11-11
         },
         {
           id: 2,
           todo_detail: "eat",
           status: 1,
           will_finish_date: 2018-11-11
         }
      ]
   }

我的代码是

getUserProject: (userId, select = '*', groupBy) => {
return knex('user_project')
  .join('projects', 'projects.id', 'user_project.project_id')
  .join('project_roles', 'project_roles.id', 'user_project.role_id')
  .join('project_todos', {
    'projects.id': 'project_todos.project_id',
    'project_todos.user_id': userId
  })
  .where('user_project.user_id', userId)
  .groupBy(groupBy)
  .select(select)
  }

这是错误的

UnhandledPromiseRejectionWarning:错误:ER_PARSE_ERROR:您的SQL语法有错误;您可能会发现错误。在第1行的“ project_todos.todo_detail”,“ project_todos.status”,“ project_todos.will_finish_da”附近检查与MySQL服务器版本相对应的手册以使用正确的语法

感谢您的提前帮助

0 个答案:

没有答案