Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

REST API: create relationship during POST ?

default discord avatar
florianmsftlast year
2

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 ?

  • default discord avatar
    hendrik01last year

    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;
    }
  • default discord avatar
    florianmsftlast year

    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 on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.