Max B
Max B

Reputation: 253

How to POST relation in Strapi

I'm trying to do a POST to the Strapi API and can't seem to figure out how to attach a 'has and belongs to many' (many to many) relationship.

I've already tried the following body's:

events: ["ID", "ID"]
name: "name"

&

events: [ID, ID]
name: "name"

Which regarding the docs should be right, I think.

There's no error, I get a '200 OK' response. It adds the record but without the relations.

Event.settings.json:

{
  "connection": "default",
  "collectionName": "events",
  "info": {
    "name": "event",
    "description": ""
  },
  "options": {
    "increments": true,
    "timestamps": [
      "created_at",
      "updated_at"
    ],
    "comment": ""
  },
  "attributes": {
    "name": {
      "type": "string"
    },
    "artists": {
      "collection": "artist",
      "via": "events",
      "dominant": true
    }
  }
}

Artist.settings.json:

{
  "connection": "default",
  "collectionName": "artists",
  "info": {
    "name": "artist",
    "description": ""
  },
  "options": {
    "increments": true,
    "timestamps": [
      "created_at",
      "updated_at"
    ],
    "comment": ""
  },
  "attributes": {
    "name": {
      "required": true,
      "type": "string"
    },
    "events": {
      "collection": "event",
      "via": "artists"
    }
  }
}

I'm using the standard SQLite database, strapi version 3.0.0-beta.13 and tried the request through Postman, HTML & curl.

I would love to know how to attach the relation on POST

Update 23-07:

Did a fresh install of Strapi and now everything is working.

Upvotes: 16

Views: 20964

Answers (3)

dpoerschke
dpoerschke

Reputation: 68

This is (still? again?) a bug in Strapi, see: https://github.com/strapi/strapi/issues/12238 As a workaround you need to add the find-permission to the user / role who is performing the request for the related content type (you want to check first if this is a security issue for your scenario or not - alternatively you might want to try Paratron's approach which is described in the comments).

Upvotes: 1

Harita Ravindranath
Harita Ravindranath

Reputation: 470

Late reply. Hoping this might help someone!

Right now I am using Strapi v4.3.2 and was facing the same issue. I overcame this by overriding the default core controller for create as explained in official docs. Relations are now visible!

async create(ctx) {
 const { data } = ctx.request.body;

 const response = await strapi.entityService.create(
    "api::collection.collection",
    {
      data: data,
    }
  );

 return {response}
}

Upvotes: 0

Jim LAURIE
Jim LAURIE

Reputation: 4120

I think it's because your set you ID as a String instead of an Integer

{
  events: [1, 2],
  name: "My name"
}

And here 1 and 2 are the IDs of events you want to add.

Upvotes: 5

Related Questions