Hi all,
I'm having a N+1 query issue between a relationship of 3 tables.
[2021-06-01 10:41:02] local.INFO: Detected N+1 Query
[2021-06-01 10:41:02] local.INFO: Model: App\User
Relation: App\Dealer
Num-Called: 13
Call-Stack:
I've got a table called User and a Dealer table. The relationship between both is AuthorisedDealers with the following structure:
id
user_id
dealer_id
created_at
.... and other fields
I've done the following query
user::with(['authorisedDealers'])->where(...)->get();
And, in my loop:
foreach ($user->authorisedDealers as $dealer) {
$authorisedDealers[] = $dealer->cod;
}
Here I'm having the N+1 problem and, honestly I don't know how to solve it, I've tried with
user::with(['authorisedDealers.dealer'])->where(...)->get();
and so on, but I've got an error in the query that says that it's not able to found the table.
I don't know if I've to change the table "authorisedDealers" to "userDealers"
In the User model I've got the following relationship:
public function authorisedDealers(): BelongsToMany
{
return $this->belongsToMany(Dealer::class, 'authorised_dealers', 'user_id', 'dealer_id');
}
Do you have any clue? I'm a bit stucked with this issue, I'm working right now doing performance tasks.
Many thanks in advance.