I was wondering if it is possible to create relationship documents via a single CRUD create operation?
Like, I have Documents and Sources Collections. DocumentCollectionType has a "relationship" field to 1 source.
POST /api/documents
{
title: "Doc title",
source: {
organisation: "Foobar",
url: "..."
}
}
==> should create a "document" item in the documents collection AND a "source" item in the sources collection in one POST request
Right now, the only way I see is creating the source first, and then reference that one by id when creating the Document.
REST API: create relationship on during POST ?
REST API: create relationship during POST ?
would recommend to use Collection:beforeChange Hooks:
https://payloadcms.com/docs/hooks/collections#beforechange
const beforeChangeHook: CollectionBeforeChangeHook = async({ req, doc, operation }) => {
if (operation !== 'create') return doc;
const source = await req.payload.create({
collection: 'sources',
data: {}
});
doc.source = source.id;
return doc;
}
great tip, thanks. Not exactly what I was trying to do (I wanted the logic to live outside of Payload), but I will consider this approach.
Star
Discord
online
Get dedicated engineering support directly from the Payload team..