John Davidson

php - Duplicate queries even if relationships are eager loaded

0 comments
Message:


I am fetching a collection of invoices like below in a Laravel Command class:


$invoices = Invoice::query()
->with('lease.activeTenant')
->whereOverdue()
->whereDate('payment_due_date', Carbon::now()->subWeekdays(5))
->get();

As you can see, I eager load the relationships: lease and lease->activeTenant.


For each invoice, I want to trigger a job that creates a PDF file and after that send out a notification to the tenant:


$invoices->each(function (Invoice $invoice){
Bus::batch([
new GenerateClaimLetter($invoice),
])->finally(function (Batch $batch) use($invoice) {
$invoice->lease->activeTenant->notify(new InvoiceClaimNotification($invoice));
})->dispatch();

});

The above code executes 41 queries in total - 28 of these are duplicates. The duplicates are:


select * from `tenants` where `state` = 'active' and `tenants`.`lease_id` in (1)    
select * from `leases` where `leases`.`id` in (1)
select * from `invoices` where `invoices`.`id` = 1 limit 1

These queries get executed multiple times - probably due to that I am accessing the relationships inside the job GenerateClainLetter and in the notification InvoiceClaimNotification. Example:


//GenerateClaimLetter.php

public function __construct(protected Invoice $invoice){}

public function handle()
{
$lease = $this->invoice->lease;

$content = view('layouts.claim-letter', [
'invoice' => $this->invoice,
'lease' => $lease,
'tenant' => $lease->activeTenant,
])->render();

//...

}

I don't quite understand why so many duplicate queries are generated. The above is only if there is one invoice in the system!


Can anybody help me out in terms of reducing the number of duplicate queries?



My Answer:
> with('customer')_ - - with('items')_ - - get();However, when I loop through the invoices and try to access the customer or items relationship, additional queries are being executed for each invoice. Why is this happening even though I have eager loaded the relationships?

Rate this post

4 of 5 based on 9919 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us