Search code examples
sqlmodelnosqlforeign-keysloopbackjs

Tags relationship in loopback 3


In Loopback how can I create tags? For example there are projects

{
  id,
  name
}

and there are tags collection with the similar model Now the project needs to have multiple tags, and the same tag can be used in multiple projects.

For example while creating a project, the user may type already existing tags, or new tags, and those should be added to the project.

I can't find the exact relationship I need in the loopback framework. How do you do that?


Solution

  • TLDR

    1. CREATE TABLE ProjectTag (id AUTO INCREMENT PRIMARY KEY, project_id INTEGER, tag_id INTEGER);

    2. $ lb relation Project has and belongs to many Tag

    3. POST localhost:3000/api/Project

    4. POST http://localhost:3000/api/Projects/{ProjectId}/Tags

    The first step creates the table which links Projects to Tags.

    The second creates the relation in loopback and modifies your Project.json relations

    The third creates a new Project

    And the fourth Creates a new tag for that project. There are a bunch more options in the REST explorer.

    EDIT

    To add a tag which already exists to a project use PUT /Projects/{PROJECT_ID}/Tags/rel/{TAG_ID}

    DETAILS

    https://loopback.io/doc/en/lb3/HasAndBelongsToMany-relations.html https://loopback.io/doc/en/lb3/HasManyThrough-relations.html

    hasAndBelongsToMany is essentially the same has hasManyThrough, except the through model is implicitly created.

    To implement the HasManyAndBelongsToMany a table must exist which maps one to the other. If you add the relation to the Project model, it will be called ProjectTag (which I'll define has a loopback model because I don't know your RDBMS).

    {
      "name": "ProjectTag",
      "properties": {
        "projectId": {
          "type": "Number"
        },
        "tagId": {
          "type": "Number"
        },
        "id": {
          "type": "Number"
        }
      }
    }
    

    You can create the relation with lb relation. Which will put this into one of your models. (My model was stackoverflow1)

    "stackoverflow2s": {
      "type": "hasAndBelongsToMany",
      "model": "stackoverflow_2",
      "foreignKey": "",
      "options": {
        "nestRemoting": true
      }
    }
    

    For example while creating a project, the user may type already existing tags, or new tags, and those should be added to the project.

    You'll have to create the project first POST localhost:3000/api/Project

    Then you can use POST http://localhost:3000/api/Projects/{ProjectId}/Tags To add tags to that specific object.