RafaelMunoznl
2 months ago
178
2
Laravel

Get resulte WHEREHAS is a condition in a related table/model

Posted 2 months ago by RafaelMunoznl

Hi there,

I have a three models/tables: Users, Employee and Appointments

The relations are : User hasOne Employee Employee hasMany Appointments User hasManyThrough Appointments

Appointments table has a 'date' column which is a DATETIME type data.

I manually seeded the database with one appointment for user.id = 1 on today '2019-11-05 09:00:00'

I am trying to get the Appointments of the day of every employee and each employee. So I did:

        $todayAppointments = User::where('user_id', '=', $user->id)
            ->with('appointments')
            ->with('employee')
            ->whereHas('appointments', function ($query) {
                $query->where('appointments.date', '=', today());
            })
            ->get();

But the results in $todayAppointments comes empty. If I delete the whereHas statement, I get the one appointment and the rest of the appointmnets in other days.

I could use DB::table('users')->join.... but I would lose the advantage of the Eloquent relations, which I am using all around in my application.

Am I missig something?

Please sign in or create an account to participate in this conversation.