Prisma:模型和关系 1-n

Prisma : Models and Relationship 1-n

我有两个 table UserTasks 一个用户可以有很多任务,但是我想查询 return 一个特定的任务,获取详细信息对于任务,作者和从用户 table 分配给用户,通常会使用别名来完成。 DB 是 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])
}

API:

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",
  },
}

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

  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' }
}