3

I'm trying to create a model for items that are related to each other. One could think of a twitter-like case where users are following each other. I tried to write the 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": []
}

I can create users with curl, but the model doesn't allow me to POST the followers or following users to 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 the function for creating the relation between two existing items myself or is there just a problem with my model definition? Any help would be appreciated.

Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55
Älhoo
  • 91
  • 1
  • 5

1 Answers1

1

Self through :

In some cases, you may want to define a relationship from a model to itself. For example, consider a social media application where users can follow other users. In this case, a user may follow many other users and may be followed by many other users. The code below shows how this might be defined, along with corresponding keyThrough properties:

common/models/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'});

pleas take attention to 'through' property in create haseMany relation and next 'belongsTo' may be resolve your issue.

Vahid Moradi
  • 791
  • 7
  • 16