edica
edica

Reputation: 339

Laravel eloquent builder, 3 tables with relations

I have 3 models that are: contracts, centers and user_centers.

The relationship between contracts and centers is 1 to N (1 center has N contracts)

And the relation between centers and user_centers, is 1 center has N user_centers.

I'm trying to eloquent a function that returns contracts by filtering by a user_id (user_centers table)

For that I do the following

    $query = Contract::query();
    $user_id = $request->query('userId');

    $query->when(request('user_id'), function ($q) use ($user_id) {
        $q->whereHas('centers.user_centers', function ($q) use ($user_id) {
            $q->where('user_id', $user_id);
        });
    });

This does not work and I do not know if I have not understood the relationship or eloquent.

Thank you

Upvotes: 0

Views: 103

Answers (1)

Vildan Bina
Vildan Bina

Reputation: 330

Just add a function on modal

class Contracts extends Model {
     ...
     public function centres()
     {
         $this->hasMany(Centres::class, 'centre_id', 'id');
     }
}

When for 1 centers with many user_centres use this function in model:

class Centers extends Model {
     ...
     public function user_centers()
     {
         $this->hasMany(user_centers::class, 'user_centers_id', 'id');
     }
}

and eloquent :

Contract::with('centres')->get();

Upvotes: 1

Related Questions