1

我有两个表UserTasks一个用户可以有很多任务,但是我想要一个查询来返回一个特定的任务,获取任务的详细信息,作者并从用户表中分配给用户,通常会使用别名来完成。数据库是 mysql - 谢谢

//schema.prisma

model User {
  id         Int    @id @default(autoincrement())
  taskby     Task[] @relation("taskBy")
  taskto     Task[] @relation("taskTo")
}

model Task {
  id              Int      @id @default(autoincrement())
  created_at      DateTime @default(now())
  updated_at      DateTime @updatedAt
  assigned_to_uid Int
  assigned_by_uid Int
  assigned_to     User     @relation("taskTo",fields: [assigned_to_uid], references: [id])
  assigned_by     User     @relation("taskBy",fields: [assigned_by_uid], references: [id])
}

接口:

if (id) {
    res = await prisma.task.findUnique({
      where: { id },
      include: {
        assigned_to: true
      },
      include: {
        assigned_by: true
      },
    })
  } else {...

期望的回应:

{
  "id": 2,
  "taskid": 2,
  "assigned_to_uid": 1,
  "assigned_by_uid": 2,
  "assigned_by": {
    "id": 2,
    "firstName": "user2",
  },
"assigned_to": {
    "id": 1
    "firstName": "user1",
  },
}
4

1 回答 1

0

您应该能够使用以下查询获得所需的响应:

  if (id) {
    const response = await prisma.task.findUnique({
      where: { id },
      include: {
        assigned_to: true,
        assigned_by: true,
      },
    });

    console.log(response);
  }

对上述查询的响应:

{
  id: 1,
  created_at: 2022-02-28T07:22:06.917Z,
  updated_at: 2022-02-28T07:22:06.918Z,
  assigned_to_uid: 2,
  assigned_by_uid: 1,
  assigned_to: { id: 2, firstName: 'Jane', lastName: 'Doe' },
  assigned_by: { id: 1, firstName: 'John', lastName: 'Doe' }
}
于 2022-02-28T07:26:20.763 回答