Update ad whose apartment has m2m relatioship with contents through apartment_contents join table

I want to implement an edit function for ad. I don't want to update contents themselves, but replace apartment's relationships with contents with a new one.
3 Replies
Prisma AI Help
You've gone full bot mode! Let me fetch that AI answer for you ASAP. To update an ad and replace its apartment's relationships with contents through the apartment_contents join table, you'll need to use an explicit many-to-many relationship update approach in Prisma. Based on the information provided in the knowledge sources, here's how you can implement this: 1. First, delete the existing relationships in the join table. 2. Then, create new relationships between the apartment and the contents. Here's an example of how you can implement this:
// Step 1: Delete existing relations for the apartment
await prisma.apartment_contents.deleteMany({
where: {
apartmentId: apartmentId,
},
});

// Step 2: Update the ad and create new content relations for the apartment
await prisma.ad.update({
where: {
id: adId,
},
data: {
// Update other ad fields here
apartment: {
update: {
contents: {
create: newContents.map(contentId => ({
content: {
connect: { id: contentId }
}
}))
}
}
}
},
});
// Step 1: Delete existing relations for the apartment
await prisma.apartment_contents.deleteMany({
where: {
apartmentId: apartmentId,
},
});

// Step 2: Update the ad and create new content relations for the apartment
await prisma.ad.update({
where: {
id: adId,
},
data: {
// Update other ad fields here
apartment: {
update: {
contents: {
create: newContents.map(contentId => ({
content: {
connect: { id: contentId }
}
}))
}
}
}
},
});
In this example, apartmentId is the ID of the apartment associated with the ad, adId is the ID of the ad you're updating, and newContents is an array of content IDs that you want to associate with the apartment. This approach is based on the workaround described in the Explicit many-to-many relationship updating the relation table is not working discussion. It's important to note that this method requires two separate operations and might not be as efficient or atomic as a single set operation in implicit many-to-many relations. Remember to adjust the model names and field names according to your specific Prisma schema.
Swagheili
SwagheiliOP4d ago
@Prisma AI Help But the schema is generated from a Django migration, so I have to use it or else the changes will break Django.
Nurul
Nurul3d ago
Hey, if you would like to continue the conversation with the bot, you can use #ask-ai channel.
But the schema is generated from a Django migration, so I have to use it or else the changes will break Django.
I didn't understand this part. Do you mean you are using prisma client python?

Did you find this page helpful?