A user can have many followers and the user can follow many users also. This is a many-to-many relationship.

To define this, open app/Models/User.js and add the code below to it:

// app/Models/User.js

followers () {
    return this.belongsToMany(
        'App/Models/User',
        'user_id',
        'follower_id'
    ).pivotTable('followers')
}

The belongsToMany relationship makes use of an additional 3rd table called pivot table to store foreign keys for the related models. Recall from the lesson where we created migration for followers, we said it will make use of the User model. So both relationships (followers and following) will be defined on the User model. The follower table wil be used as a pivot table.

Table of Contents

    We pass user_id as the foreign key for the current model and follower_id as the foreign key for the related model.

    By default, AdonisJS will expect a follower_user table as the pivot table. But our pivot table has a different name, so we need to specify it while defining the relationship with pivotTable().

    Next, we define the inverse relationship. Still within app/Models/User.js, add the code below:

    // app/Models/User.js
    
    following () {
        return this.belongsToMany(
            'App/Models/User',
            'follower_id',
            'user_id'
        ).pivotTable('followers')
    }

    Here we pass follower_id as the foreign key for the current model and user_id as the foreign key for the related model.

    Chimezie Enyinnaya

    20 posts

    Software Developer [PHP Laravel JavaScript NodeJS AdonisJS VueJS] | movie lover | run http://openlaravel.com