Search code examples
node.jsrelationshipstrapi

Custom junction table in strapi


I have recently started working on strapi and was looking at the relations inside model in their documentation. My scenario is as follows. I have a model named course and another named tag. They have many to many relationship between them.This is what ./api/course/models/course.settings.json has when I made the relation between them named as tag2.

 {
  "connection": "default",
  "collectionName": "course",
  "info": {
    "name": "course"
  },
  "options": {
    "increments": true,
    "timestamps": true
  },
  "attributes": {
    "image_link": {
      "type": "string"
    },
    "created_by": {
      "columnName": "created_by_id",
      "plugin": "users-permissions",
      "model": "user"
    },
    "updated_by": {
      "columnName": "updated_by_id",
      "plugin": "users-permissions",
      "model": "user"
    },
    "title": {
      "type": "string"
    },
    "short_description": {
      "type": "text"
    },


    "slug": {
      "type": "string",
      "unique": true
    },
    "tags2": {
      "collection": "tag",
      "via": "courses",
      "dominant": true
    }
  }
}

When I specify the relation using the admin panel strapi itself made a junction table named as courses_tags_2_s__tags_courses.

Here is what tag model looks like

  {
    "connection": "default",
    "collectionName": "tag",
    "info": {
      "name": "tag",
      "mainField": "ui_label"
    },
    "options": {
      "increments": true,
      "timestamps": true
    },
    "attributes": {
      "code": {
        "type": "string"
      },
      "description": {
        "type": "string"
      },
      "created_by": {
        "plugin": "users-permissions",
        "model": "user",
        "columnName": "created_by_id"
      },
      "updated_by": {
        "plugin": "users-permissions",
        "model": "user",
        "columnName": "updated_by_id"
      },
      "ui_label": {
        "type": "string"
      },
      "courses": {
        "via": "tags2",
        "collection": "course"
      }
    }
  }

I have a couple of questions

1) Is there a way I can set up the junction table as courses_tags ? i.e overriding the strapi one

2) I have set my mainField as "ui_label" in tag.settings.json but in the admin panel while editing course table content(rows in course table), in the related field of tag2 I see "code" field shown there instead of "ui_label". How to set the mainField?

Note: I have setup strapi with mysql server.


Solution

  • so to answer your first question, there is currently no way to override the join table between two models. This is totally auto-generated by Strapi.

    For the second question, this part of the docs is out to date. To manage display information you will have to use the content manager configuration in the admin panel.

    Here a short video - https://www.youtube.com/watch?v=tzipS2CePRc&list=PL7Q0DQYATmvhlHxHqfKHsr-zFls2mIVTi&index=5&t=0s