Multiple Joins in Eloquent from local scopes

Viewed 77

Got a question regarding Eloquent and the scope functionality:

Assuming two scopes:

class Result extends Model {

   public function scopeIsRace($query) {
        return $query
            ->join('sessions', 'sessions.id', '=', 'results.session_id')
            ->where('sessions.type', 10)
   }

   public function scopeIsOfficial($query) {
        return $query
            ->join('sessions', 'sessions.id', '=', 'results.session_id')
            ->join('events', 'events.id', '=', 'sessions.event_id')
            ->where('events.regular_event', 1);
   }
}

Calling both of them performs two joins of sessions and the resulting query looks sth like this (doesnt work)

select * from `results` inner join `sessions` on `sessions`.`id` = `results`.`session_id` inner join `sessions` on `sessions`.`id` = `results`.`session_id` inner join `events` on `events`.`id` = `sessions`.`event_id` where `driver_id` = 24 and (`sessions`.`type` = 10 or `sessions`.`type` = 11) and `events`.`regular_event` = 1

How do I prevent the double join on sessions?

1 Answers

Thank you so much @Nima. Totally forget about an advanced whereHas. Used a structure llke this from your suggested question and it works perfectly fine:

public function scopeIsRace($query) {
    return $query->whereHas('session', function($query){
        $query->where('type', 10);
    });
}

public function scopeIsOfficial($query) {
    return $query->whereHas('session', function($query) {
        return $query->whereHas('event', function($query2) {
            $query2->where('regular_event', 1);
        });
    });
}
Related