How do I update an relation? #215
-
Hi, how do I update a relationship? I.e if I want to add an extra entry to an existing manyOf relationship. Example code: {
post: {
id: primaryKey(() => faker.unique(faker.datatype.number)),
title: faker.datatype.string,
images: nullable(manyOf('image')),
},
image: {
id: primaryKey(() => faker.unique(faker.datatype.number)),
url: faker.datatype.string
}
} In an msw rest handler I got something like this: rest.post('/api/images', (req, res, ctx) => {
const postId = parseInt(req.body.get('postId'),10)
const image = db.image.create({url: req.body.get('url')})
const post = db.post.findFirst({...})
post.images.push(image)
db.post.update({
where: {id: {equals: postId}},
data: {
images: post.images
}
})
} I'm sure there is something haven't understood. How can I ensure that the image gets added to posts.images ? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi, @tarjei. Here's how you can update a const db = factory({
post: {
id: primaryKey(String),
images: manyOf('image')
},
image: {
id: primaryKey(String),
url: String
}
})
rest.post('/api/images', (req, res, ctx) => {
// Create a new "image" entity.
const newImage = db.image.create({
url: req.body.url
})
// Update a certain post(s) by adding a new image
// to the existing "post.images" relationship.
const nextPost = db.post.update({
where: { id: { equals: 'some-post' } },
data: {
images(prevImages) {
// Grab the previous value of "post.images"
// and add the newly created post to it.
return prevImages.concat(newImage)
}
}
})
// Optionally, consider concluding with a HTTP response.
return res(ctx.status(201), ctx.json(newImage)))
}) The main point here is that each property in the data/src/model/updateEntity.ts Line 38 in df18b9d So it accepts the previous value of this particular property ( |
Beta Was this translation helpful? Give feedback.
Hi, @tarjei.
Here's how you can update a
manyOf
relation by pushing a new entity to the relational value: