I have the following Prisma model definitions:
model Pet {
id Int @id @default(autoincrement())
name String
kind String
owner Owner @relation(fields: [ownerId], references: [id])
ownerId Int
}
model Owner {
id Int @id @default(autoincrement())
name String
age Int
pets Pet[]
}
I'm trying to write a query that disconnects a Pet from an Owner using the following code:
await prisma.pet.update({
where: {
id: 1
},
data: {
owner: {
disconnect: true
}
}
});
As stated in the docs here, this should disconnect the relation.
However, there seems to be a type error on the disconnect
property of owner
. The type error:
Type '{ disconnect: true; }' is not assignable to type 'OwnerUpdateOneRequiredWithoutPetsNestedInput'.
Object literal may only specify known properties, but 'disconnect' does not exist in type 'OwnerUpdateOneRequiredWithoutPetsNestedInput'. Did you mean to write 'connect'?ts(2322)
I have tried setting owner
to undefined
but that does not seem to update the database in any way (it does typecheck). I also tried setting ownerId
to undefined
and it runs and check but again the database doesn't seem to update.
I'm using SQLite and Prisma Studio. Prisma & Prisma client version 14.4 and Typescript 5.0.
How would I fix this?
In your case, you have a one-to-many relationship between Owner
and Pet
, where an Owner can have many Pets, but a Pet can have only one Owner.
When you try to disconnect a Pet from an Owner using the following code:
await prisma.pet.update({
where: {
id: 1
},
data: {
owner: {
disconnect: true
}
}
});
you're getting a type error because the disconnect property is not valid in this context.
In a one-to-many relationship, the disconnect operation is only applicable on the "many" side of the relation. You can disconnect a Pet from an Owner by operating on the Owner model, not the Pet model.
This query should work as you expect:
await prisma.owner.update({
where: {
id: ownerId // the id of the owner who owns the pet
},
data: {
pets: {
disconnect: {
id: 1 // the id of the pet you want to disconnect
}
}
}
});
But please note that the above query will only work if your schema allows for the ownerId field to be nullable. If it doesn't, you'll need to update your Prisma schema to make the ownerId field nullable by adding a (?
)
The schema would look something like this:
model Pet {
id Int @id @default(autoincrement())
name String
kind String
owner Owner? @relation(fields: [ownerId], references: [id])
ownerId Int?
}
model Owner {
id Int @id @default(autoincrement())
name String
age Int
pets Pet[]
}