Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loopback "hasManyThrough" relation. Where to add it?

I have a User entity and a Hobbie entity, both have their models defined in Loopback and I see them in the API explorer.

I have a table UserHobbie that links User and Hobbie in a ManyToMany relation. I'm tryting to declare a loopback hasManyThrough relation such as

User.hasMany(Hobbie, {through: UserHobbie});

but I cannot seem to do it well, for it doesn't show up in the explorer. I've declared it in /server/server.js right after the bootstrapping section, and I've tried doing it in /common/User.js and /common/Hobbie.js (but in either one of them, the other model isn't visible).

Is there a proper syntax to add this in User.json or Hobbie.json? That would be my preferred way to go, since anything I put in the json definition shows up right in the explorer.

like image 586
ffflabs Avatar asked Dec 02 '25 21:12

ffflabs


1 Answers

To solve the problem within your Model JSON, I'll outline the Solution below. However, using a "hasAndBelongsToMany" Relationship would solve your problem more simply and I'll outline that below also.

Within your User.json:

  "relations": {
    "Hobbies": {
      "type": "hasMany",
      "model": "Hobbie",
      "through": "UserHobbie",
      "foreignKey": "hobbieId"
    }
  }

Within your Hobbie.json:

  "relations": {
    "Users": {
      "type": "hasMany",
      "model": "User",
      "through": "UserHobbie",
      "foreignKey": "userId"
    }
  }

Your UserHobbie.json would look like this (note that you DO NOT define userId OR hobbieId within "properties":

{
  "name": "UserHobbie",
  "plural": "UserHobbies",
  "base": "PersistedModel",
  "properties": {
    "id": {
      "type": "String",
      "id": true
    }
  },
  "validations": [],
  "relations": {
    "Users": {
        "type": "belongsTo",
        "model": "User",
        "foreignKey": "userId"
    },
    "Hobbies": {
        "type": "belongsTo",
        "model": "Hobbie",
        "foreignKey": "hobbieId"
    }
  },
  "acls": [],
  "methods": []
}

THIS SIMPLER WAY TO DO THIS IS BELOW:

DON'T EXPLICITLY CREATE A UserHobbies Model. Loopback will AUTOMATICALLY create a Join Model for you.

Within your User Model:

  "relations": {
    "Hobbies": {
      "type": "hasAndBelongsToMany",
      "model": "Hobbie"
    }
  }

Within you Hobbie Model:

  "relations": {
    "Users": {
      "type": "hasAndBelongsToMany",
      "model": "User"
    }
  }

If you want to do this in code, YOU ARE CORRECT, there are Bootstrap Timing Issues that keep these Relationships from appearing in Explorer. I will add another response soon to show you how to make that work too.

like image 61
tonyStrong Avatar answered Dec 04 '25 14:12

tonyStrong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!