Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jarjis's avatar

Filtering data by Multiple Relationship Table

I have 3 tables:

Table-1: users =>id,name,email,password Table-2: applications=> id, user_id,division_id,district,address,photo Table-3: results => id, user_id,mark

Relation: Users with results table one-to-many relationship & users with applications table one-to-one relationship.

I fetched data from the results table below

public function results(Request $request){
        $results = Result::with(['user'=>function ($q){
            $q->with(['application'=>function($p){
                $p->where('division_id',1);
            }]);
        }])->orderBy('mark','desc')->paginate(10);
        return $results;
}

when I filter the applications table where the condition shows me all application table data... I want to exact data. how could I do this please help me.

—Thanks!

0 likes
2 replies
SilenceBringer's avatar
Level 55

@jarjis try something like:

$results = Result::with('user.application')
    ->whereHas('user.application', function ($query) {
        $query->where('division_id',1);
    })
    ->orderBy('mark','desc')
    ->paginate(10);
1 like

Please or to participate in this conversation.