Laravel where condition within ‘with’

  Kiến thức lập trình

I have an eloquent query:

        $cameras=Jump::Video()
            ->with('flight','flight.aircraft','flight.airfield')
            ->with('student','student.logininfo','student.logininfo.reservations')
            ->with('camera','camera.status')
            ->whereBetween('data',[ $from, $to])
            ->orderBy($sortBy, $orderDesc)
            ->paginate($request->perPage);

and relations between student, logininfo and reservations

Model Jump.php

    public function scopeVideo($query)
    {
        return $query->where('exercise', '104');
    }

    public function student() {
        return $this->hasOne('AppModelsPersonalData','id','student');
    }

Model PersonalData.php

    public function logininfo() {
        return $this->hasOne('AppUser','id_user','id');
    }

Model User.php

    public function reservations() {
        return $this->hasMany('AppModelsReservation','user_id', 'id');
    }

I’d like to get only Jumps where ‘type’ in table ‘reservation’ (model Reservation) is equal $request->type

I was trying:

->where('student.logininfo.reservations','=',$request->type)

OR

->whereHas('student.logininfo.reservations',function($query) use ($request) {
    return $query->where('type','=',$request->type)
})

and it didn’t work. Any suggestions?

LEAVE A COMMENT