Search code examples
laraveleloquentmodels

LARAVEL - How to create an indirect relation between 3 models


I have 3 Models: User, Pet and Clinic.

Let's assume the tables: users, pets and clinics. The relation is, one user can have more than one pet, and one pet only have one clinic.

On the table "Pets" i have a FK to the user_id and another one to the clinic_id.

I want to do something like:

$user->clinics(); 

on the User model to return all the distinct clinics associated with the user. Now i can only do:

$user->pets()->with('clinics); 

but i want to return only the distinct clinics.

User modal:

public function pets()
{
    return $this->hasMany('Petable\Models\Pet', 'user_id', 'id');
}

Pet modal:

public function clinic()
{
    return $this->belongsTo('Petable\Models\Clinic', 'clinic_id', 'id');
}

Any suggestion ?


Solution

  • The following should be sufficient:

    public function clinics()
    {
        return $this->belongsToMany('Petable\Models\Clinic', 'user_pets')->distinct();
    }
    

    And then this allows you to call

    $user->clinics();