mercredi 10 juillet 2019

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire