How to save a new many-to-many relation

Hey guys, I’ve a many-to-many relation where every user can follow another users and be followed by them. In documetation I’ve seen I need a pivot table and I create it and the relations on User model, but how can I create a new “follow”? I dont get how to do that, to create a new row on the pivot table. Let me show what I’ve done until now

let’s pretend follows() is in user model.

in controller or wherever you want to save you just call something like this:

const followee = await User.find(2) //user we want to follow
const user = await User.find(1) //us
await user.follows().attach([])

see more here

edit: also I think you have typo in your table name.

1 Like

@Tsume I got your point and started from scratch again, but I’m facing another error could you please help me to solve it? See the images below for more context, I’ve tried as you said before


1 Like

First, your FollowerFollowings model should contain this: (if you have pivot model)

  static get table () {
    return 'follower_followings'

And then in User model:

follows() {
    return this.belongsToMany('App/Models/User').withPivot(['following_id']).pivotModel('App/Models/FollowerFollowings')

Note that I don’t know whether FollowerFollowings model exists.

1 Like

I could understood! thank you!!