Many-to-one or One-way relationships
See original GitHub issueProblem
I find it problematic that relations can only be modelled as one->many instead of many->one.
An example use case:
model Post {
id String @id
User User[] @relation(fields: [userIds], references: [id])
userIds String[]
}
model User {
id String @id
likes Post[] @relation(references: [id], fields: [likedPostIds])
likedPostIds String[]
}
This simple data model would allow me to use prisma’s nice Fluent API, and do things like User.likes()
. However, this is not scalable at all, if a Post has a million likes, the userIds
array is going to be huge.
Suggested solution
Ideally, I would like to have the flexibility to decide for myself how the data is going to be structured. For my use case, I will never need to follow the relation from Post=>User
, only User=>Post
.
I wish the formatter would allow one-way relations, that way it could be as simple as:
model Post {
id String @id
}
model User {
id String @id
likes Post[] @relation(references: [id], fields: [likedPostIds])
likedPostIds String[]
}
Alternatives
The only alternative is to have a very granular “join table”, such as this:
model Post {
id String @id @map("_id")
LikesByUser LikesByUser[]
}
model LikesByUser {
userId String
post Post @relation(fields: [postId], references: [id])
postId String
User User @relation(fields: [userId], references: [id])
@@id([userId, postId])
}
model User {
id String @id @map("_id")
LikesByUser LikesByUser[]
}
Other than inconvenience, the downside of doing this is that it isn’t very storage efficient.
Issue Analytics
- State:
- Created a year ago
- Reactions:7
- Comments:16 (6 by maintainers)
Top GitHub Comments
We’re currently looking for a way to add one-way relations as well. We call these “references”. I’m not sure if this belongs on this issue, but consider a scenario where you might want to add “related items” to a post or product where it’s not only unnecessary, but undesirable to create a corresponding “link” on the other side of the relation. This is a very common pattern, and ideally we would be able to support this in a first class way with prisma. Instead, we have a number of different one-to-many, or many-to-many relations where one side of the relation will never be used.
An alternative would be to use array fields, or json, etc. But that defeats the purpose of using prisma for the fluent API, referential integrity, etc.
Any update on this? One way relationships are integral for our schema design. Is there any way to achieve that currently in prisma till official support lands?