![](/img/trans.png)
[英]How to create one to many relationship from many to many join table in Prisma
[英]Prisma can a one to many relationship be created from a relation table?
我正在使用 Prisma 和 MySQL 創建一個鍛煉應用程序。
我在用戶和指定程序之間存在多對多關系,如 model 'ProgramEnrollment' 所示。 我遇到的問題是我希望用戶記錄他們的個人鍛煉集。
我的想法是創建一個新的 model“LoggedWorkoutSet”,然后通過一對多關系將其連接到 model“ProgramEnrollment”,這意味着一個“ProgramEnrollment”可以有多個“LoggedWorkoutSet”。 這似乎對我不起作用,問題在於嘗試在這里定義關系時:
program ProgramEnrollment @relation(fields: [programId], references: [id])
programId Int // relation scalar field (used in the `@relation` attribute above)
我得到的錯誤是“驗證錯誤:參數references
必須僅引用相關 model ProgramEnrollment
中的現有字段。 相關model中不存在以下字段:id'
我不知道該怎么做,任何幫助將不勝感激。
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;
使用所有 3 個表的查詢:
-- 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.