Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
Max B Avatar asked Jul 17 '19 14:07

Max B


People also ask

How do you populate a Strapi relationship?

To populate all the root level relations, use populate: '*' : const entries = await strapi. entityService.

How do you get API endpoints on a Strapi?

Strapi automatically creates API endpoints when a content-type is created. API parameters can be used when querying API endpoints to refine the results. The REST API by default does not populate any relations, media fields, components, or dynamic zones. Use the populate parameter to populate specific fields.

How do you put a Strapi on a table?

In Strapi, we can create tables by adding a Content Type. So let's dive in and create one for our Painter table. Click on Content Type Builder in the left-side menu and under Content Types click on Create new content type. Enter Painter under Display name and click Continue.


1 Answers

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.

like image 158
Jim LAURIE Avatar answered Oct 13 '22 17:10

Jim LAURIE