PivotModel implementation help


#1

Hi.

I want to create a relation between users and that relation should be defined as “friends”, “colleagues”,“enemies”,“other”.

I have the following tables:
users: id, name. // where all the users are stored.
links: id, name. // where all the links types are stored (friends, collegues, etc).
users_has_users: users_id, users_id1, links_id // where the relations are stored.

Image

User A can set a “friends” relation with User B and User B can set an “enemies” relation with user A.

In User.js I have defined the following

  linkedTo(){
    return this.belongsToMany(
      'App/Models/User',
      'users_id',
      'users_id1'
    ).pivotModel('UsersLink')
  }

  linkedBy(){
    return this.belongsToMany(
      'App/Models/User',
      'users_id1',
      'users_id'
    ).pivotModel('UsersLink')
  }

In UsersLink.js (users_has_users table)

  relation(){
    return this.belongsTo(
      'App/Models/Links',
      'links_id'
    )
  }

I would like to know if I’m in the right way. I don’t know how to continue and how to set the ‘links_id’ value when defining a relation.

Thanks for your help.


#2

I decided to not use PivotModel as I can’t make it work. It would be nice to have an example of a real implementation as it looks its a very asked issue.

B/R.