简体   繁体   中英

Prisma can a one to many relationship be created from a relation table?

I am creating a workout app using Prisma and MySQL.

I have a many to many relationship between a user and a prescribed program, shown in the model 'ProgramEnrollment'. The isssue I am having is I would like the user to log their personal workout sets.

My thoughts were to create a new model 'LoggedWorkoutSet' and then connect it to the model 'ProgramEnrollment' via a one to many relationship, meaning one 'ProgramEnrollment' can have many 'LoggedWorkoutSet'. This doesn't seem to be working for me, the issue is with when trying to define the relationship here:

program   ProgramEnrollment @relation(fields: [programId], references: [id])
  programId Int // relation scalar field  (used in the `@relation` attribute above)

The error I am getting is 'Error validating: The argument references must refer only to existing fields in the related model ProgramEnrollment . The following fields do not exist in the related model: id'

I'm not sure what to do, any help would be much appreciated.

model ProgramEnrollment {
  program                 Program     @relation(fields: [programId], references: [id])
  programId               Int // relation scalar field (used in the `@relation` attribute above)
  user                    User @relation(fields: [userId], references: [id])
  userId                  Int // relation scalar field (used in the `@relation` attribute above)
  assignedAt              DateTime @default(now())

  loggedWorkoutSet        LoggedWorkoutSet[]

  @@id([programId, userId])
}
model LoggedWorkoutSet {
  id              Int  @id @default(autoincrement())
  reps            Int
  weight          Int
  completed       Boolean     @default(false)

  author   ProgramEnrollment @relation(fields: [programId], references: [id])
  programId Int // relation scalar field  (used in the `@relation` attribute above)
}
CREATE TABLE Users (
    user_id ...,
    ...
    PRIMARY KEY (user_id)
) ENGINE=InnoDB;

CREATE TABLE Programs (
    pgm_id ...,
    part_of_body ... -- legs/shoulders/...
    ...
    PRIMARY KEY (pgm_id)
) ENGINE=InnoDB;

-- Many-to-many, with stats:
CREATE TABLE UserPgm (
    user_id ...,
    pgm_id ...,
    latest_date DATE ...,
    reps SMALLINT UNSIGNED NOT NULL,
    weight SMALLINT UNSIGNED NOT NULL,  -- in the normal units for this device
    PRIMARY KEY(user_id, pgm_id),
    INDEX(pgm_id, user_id)
) ENGINE=InnoDB;

A query using all 3 tables:

-- The latest workout for a user:
SELECT u.name,
       up.latest_date,
       up.reps,
       p.device_name
    FROM Users    AS u
    JOIN UserPgm  AS up  USING(user_id)
    JOIN Programs AS p   USING(pgm_id)
    WHERE user_id = 123

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM