beyondcode / laravel-query-detector

Laravel N+1 Query Detector
https://beyondco.de/docs/laravel-query-detector/usage
MIT License
1.99k stars 138 forks source link

False detection when using count? #101

Open philharmonie opened 1 year ago

philharmonie commented 1 year ago

I am using the following code to count a user's open tasks:

$tasks_count = Auth::user()->tasks()->whereCompleted(false)->count();

The plugin tells me:

Model: App\Models\User => Relation: App|Models\Task - You should add "with ('App\Models\Task')" to eager-load this relation.
Model: App\Models\Task => Relation: user - You should add
"with ('user')" to eager-load this relation.

When I do that, the issue still occurs:

$tasks_count = Auth::user()->tasks()->with('user')->whereCompleted(false)->count();

Using

$tasks_count = Auth::user()->with('tasks')->tasks()->whereCompleted(false)->count();

gives me Call to undefined method Illuminate\Database\Eloquent\Builder::tasks() but user has a tasks relationship:

class User extends Authenticatable
{
    // ...

    public function tasks()
    {
        return $this->hasMany('App\Models\Task');
    }
philharmonie commented 1 year ago

$tasks_count = Auth::user()->load('tasks')->tasks()->whereCompleted(false)->count();

mechelon commented 1 month ago

Do you get the same alert with $tasks_count = Auth::user()->tasks()->whereCompleted(false)->get();?