Search code examples
databaselaravelrelational-databasemodels

Implement Unary Many-to-Many Relation with Eloquent models [Laravel]


How I can implement Unary Many-to-Many Relation with Eloquent models

Ex: If there's a relation that User can send request friend to one or more user

I know that I have to create new model like user-request-user for example,, Primary Keys for new model will be [user1_id , user2_id] that's what I think

but how to implement this relation then ..


Solution

  • yes dear it is possible in just like ordinary many to many relationship but with a little difference. first step for many to many relation is create pivot table so you create migration for pivot table. pivot table is belongs to two table in normal many to many relation but this pivot table is belongs to a single table.if you create pivot table name "friend_request_user", so here is the migration

    public function up()
    {
        Schema::create('friend_request_user', function(Blueprint $table)
        {
            $table->integer('user_id')->unsigned()->index();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    
            $table->integer('request_user_id')->unsigned()->index();
            $table->foreign('request_user_id')->references('id')->on('users')->onDelete('cascade');
    
            $table->timestamps();
    
        });
    }
    

    now you should have two models one "User" and other as you already have "user-request-user". both models should point to same table which is "users". by default User model is point to users table but you write a property $table for pointing "users" table for "user-request-user" model so

    protected $table = 'users';
    

    in User model you just write a simple method as write in any other many to many relation... so

    public function request(){
        return $this->belongsToMany('App\user-request-user', 'friend_request_user','user_id', 'request_user_id');
    }
    

    first parameter of "belongsToMany" function is relational model, 2nd is pivot table name, 3rd is foreign key and 4th is other key use in pivot table. we write these parameters just because not follows the laravel syntax in this case. this is all, now just call this function like

    Auth::user()->request;
    

    you may also like to use opposite of function which can write on other model "user-request-user" but this is just for your need.

    public function nameOfFunction(){
        return $this->belongsToMany('App\User', 'friend_request_user', 'request_user_id', 'user_id');
    }