Hassan Saqib
Hassan Saqib

Reputation: 2767

How to select instances with multiple relations?

I have some models Featured_Course_Request, Course_Request, Response and Teacher. Featured_Course_Request hasOne Course_Request and Course_Request hasMany Response by Teacher.

I want to get the only Featured_Course_Requests on which logged in teacher has not responded (have no Response by logged in teacher.) How can I do it?

I am trying to achieve it with the following code but it is not giving correct output.

 $featured_course_request = Featured_Course_Resquest::whereRaw('remaining_coins >=  coins_per_click')->where('status', '=', 'open')
    ->whereHas('courseRequest', function($q) use ($teacher){                                                            
    $q->whereHas('responses', function($qe) use ($teacher){
        $qe->where('teacherID', '!=', $teacher->id);
            });

    });

Upvotes: 0

Views: 30

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 153020

You can target nested relations with the dot syntax: 'courseRequest.responses' further more you'll need whereDoesntHave instead of whereHas:

$featured_course_request = Featured_Course_Resquest::whereRaw('remaining_coins >=  coins_per_click')
    ->where('status', '=', 'open')
    ->whereDoesntHave('courseRequest.responses', function($q) use ($teacher){
        $qe->where('teacherID', '=', $teacher->id);
    })
    ->get();

Upvotes: 1

Related Questions