I have the following request:
$results = ResultTest::with("client", "doctor.distributor")
->whereIn("client_id", $transaction_items_unique_codes)
->get();
It returns me array of result. After I need to get additional data for each returned array item and join it to one result:
foreach ($results as $result) {
$conclusion = Conclusion::where("type_work", $result->type_work)
->where("category", $result->category)
->firstOrFail();
$types = Work::orderBy('name')->get()->pluck('name', 'id');
}
Problem is $results
contains more 100 rows, so it has issues with 100 requests to db.
CodePudding user response:
Why not just use a leftJoin
?
$results = ResultTest::query()
->with([
'client',
'doctor.distributor'
])
->leftJoin('conclusions c', function ($join) {
$join->on('result_tests.type_works', 'c.type_works')
->on('result_tests.category', 'c.category')
})
->whereIn('client_id', $transaction_items_unique_codes)
->get();
If it was just one condition, you could create a relationship and eager load it but as far as I can think of at the moment, Eloquent doesn't support defining a relationship that depends on multiple columns.