Ok, so I'm trying to figure out eager loading to improve application performance. I'm working on a service database, but am having some problems. Here is my code

$service_data = Client::join('service_requests','clients.id','=','service_requests.client_id')
    ->join('service_request_comments','service_requests.id','=','service_request_comments.service_request_id')
    ->whereNotNull('service_request_comments.time')->with('service_requests')->with('service_requests.comments')->get();

The query does properly pull the data, but it loads ALL service_requests and service_requests.comments into the first client_object, instead of loading a client object with the service_requests objects and then loading the service_request objects with the appropriate comments.

Each of these relationships are one to many...

...A client can have many service_requests
...A services_request can have many comments
...and by extention...
    ...A client can have many comments

I tried using the constraints, but that just gave me a couple dozen 500s with various syntax. Could somebody tell me what I'm doing incorrectly?

有帮助吗?

解决方案

Don't use joins if you're doing eager loading. You're essentially combining Query Builder commands with Eloquent features, and the two are conflicting. Something like this should get the same thing (skipping the where constraint for now):

$service_data = Client::with('service_requests.comments')->get();

Note that the nested with() request will automatically eager load service_requests and then their comments.

If you need the query on the comments relationship, there are a couple ways to do so, and I don't want to make assumptions about exactly what you're using for (or if it's necessary at all), so I'll skip that for now.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top