Creating self-relationship between existing elements in loopback

I am trying to create a model for items related to each other. One might think of a tweeter-like case where users follow each other. I tried to write a model like this (common / models / user.json):

{
  "name": "user",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "name": {
      "type": "string"
    }
  },
  "validations": [],
  "relations": {
    "following": {
      "type": "hasAndBelongsToMany",
      "model": "user",
      "foreignKey": "userId"
    }
    "followers": {
      "type": "hasAndBelongsToMany",
      "model": "user",
      "foreignKey": "userId"
    }
  },
  "methods": []
}
      

Run codeHide result


I can create users with curl, but the model doesn't allow me to POST subscribers or the following users for a given user:

curl -X POST -d '{"name": "Bob"}' http://localhost:3000/api/users
curl -X POST -d '{"name": "Mary"}' http://localhost:3000/api/users
curl -X POST -d '{"userId": 1}' http://localhost:3000/api/users/2/following

      

Do I need to create a function to create a link between two existing elements or is there just a problem with my model definition? Any help would be appreciated.

+3


source to share


1 answer


By yourself:

In some cases, you may need to determine the attitude of the model to yourself. For example, consider a social media app where users can follow other users. In this case, the user can follow many other users and many other users can follow. The code below shows how this can be determined, as well as the corresponding keyThrough properties:

generic / model / user.js



User.hasMany(User, {as: 'followers', foreignKey: 'followeeId', keyThrough: 'followerId', through: Follow});
User.hasMany(User, {as: 'following', foreignKey: 'followerId', keyThrough: 'followeeId', through: Follow});
Follow.belongsTo(User, {as: 'follower'});
Follow.belongsTo(User, {as: 'followee'});

      

draws attention to the property 'through'

in creating a haseMany relationship, and the following 'belongsTo'

might solve your problem.

+1


source







All Articles