beyondcode/laravel-query-detector

False detection for different relations with the same values

johanvanhelden opened this issue · 3 comments

Let's say you have a Ticket model, the ticket has an assignee, a reporter and a group relation.
The assignee and reporter are both Users. Users also have a group relation, corresponding to a Group model. And a group can be directly assigned to a ticket.

If I want to use the assignee's user group, I would do:
$ticket->assignee->group->name
And for the reporter:
$ticket->reporter->group->name
And for the ticket group itself:
$ticket->group->name

All 3 could have different values, but they could also be the same.

In order to eager load properly, I would use:

Ticket::with([
    'group',
    'reporter.group',
    'assignee.group',
])->get();

If all values are different, there are no issues. So let's say the reporter is a user with the ID of 1, and the assignee is a user with the ID of 20, both user's are in different groups, and the group directly assigned to the ticket is a group that does not belong to one of the users, everything is fine.

However, if the reporter and assignee, are both a user with ID 1, and are therefore in the same group (let's say a group with the ID 100), and the group directly assigned to the ticket is also the group with the ID 100, it will detect a few n+1 queries. Because it will query the same user 2 times (this is detected) and the same group 3 times (this is also a detection).

But these queries should be there, because I am properly eager-loading the relations. They just so happen to have the same values.

In reality even more relations are eager-loaded on the groups and these can also cause n+1 detections, in reality it might look like:

$latestTicket = Ticket::forCompany($company)
    ->with([
        'assignee.group.attributes.labels',
        'assignee.group.attributes.groups.users',

        'reporter.group.attributes.labels',
        'reporter.group.attributes.groups.users',
        
        'group.attributes.labels',
        'group.attributes.groups.users',
    ])
    ->latest()
    ->first();

There seems to be no way to fix this, or am I missing something?

This same scenario happens to me

Same happens to me

I'll close this issue now, I don't use the package anymore.