1

I have an Appointment model that has a relation to Employee and an Employee to a User. I am trying to query a list of appointments between specific dates ($weekStart and $weekEnd) and retrieve the appointments as well as the related Employees and Users.

So far this works, it returns all my Clients with all appointments and the assigned Employees/Users (Employees belong to User).

'clients' => Client::with('careType','appointments.employees.user')->get(),

However I wish to specify between dates on the appointments model. So I have this:

$data = [
  'clients' => Client::with(['appointments' => function ($query)  use ($weekStart, $weekEnd) {
        $query->whereBetween('starts_at', [$weekStart, $weekEnd]);
        }])->get(), 
]; 

In the above what is the syntax to also retrieve the employees and user models when I have a sub query?

1 Answer 1

1

You just add your other models in your Client's with() array.

$data = [
  'clients' => Client::with(['appointments' => function ($query)  use ($weekStart, $weekEnd) {
        $query->whereBetween('starts_at', [$weekStart, $weekEnd]);
        }, 'appointments.employees.user'])->get(), 
]; 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. That works. Not sure how. Does everything in the [] get evaluated as one? At first glance, I thought this would just reset the appointments and get() all rather than the query list.
Laravel's Eager Loading is a little complicated, but basically all string elements in the with statement (like appointments.employees.user) are evaluated first, and then any functions in the array will be evaluated and replace existing string elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.