AveTaylor
AveTaylor
PPrisma
Created by AveTaylor on 6/19/2024 in #help-and-questions
How to populate array in one-to-many relationship (or may be even persist)?
Hi. I have the following example models:
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
articles Article[]
}

model Article {
user User @relation(fields: [userId], references: [id])
userId String @db.ObjectId
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
articles Article[]
}

model Article {
user User @relation(fields: [userId], references: [id])
userId String @db.ObjectId
}
Then I create my user:
findOrCreate(createUserDto: CreateUserDto) {
return this.prismaService.user.upsert({
where: { email: createUserDto.email },
update: {},
create: {
email: createUserDto.email,
}
});
}
findOrCreate(createUserDto: CreateUserDto) {
return this.prismaService.user.upsert({
where: { email: createUserDto.email },
update: {},
create: {
email: createUserDto.email,
}
});
}
Then I create my article:
create(createArticleDto: CreateArticleDto) {
return this.prismaService.article.create({ data: createArticleDto });
}
create(createArticleDto: CreateArticleDto) {
return this.prismaService.article.create({ data: createArticleDto });
}
createArticleDto contains userId and thus it should connect these two models together. Then I try to find user and populate their articles:
findOne(id: string) {
return this.prismaService.user.findUnique({
where: { id },
include: {
articles: true,
}
});
}
findOne(id: string) {
return this.prismaService.user.findUnique({
where: { id },
include: {
articles: true,
}
});
}
But it does not have nor return any article. Please, tell me, what am I doing wrong and possible fixes of the situation? Thanks.
3 replies