Search code examples
phpsqllaraveleloquentlaravel-data

Laravel addSelect


I have a query, and I'm trying to add a addSelect() to it, but it won't work, and I don't know why, according to the docs it seems correct

The query:

return Project::query()
    ->with('client')
    ->with('status')
    ->with('tasks')
    ->with('tasks.user.userAvatar')
    ->with('tasks.user')
    ->addSelect([
        'number_of_tasks' => Task::where('assigned_id', auth()->user()->id)->whereNull('finished_at')->count()
    ])

I got this error:

Column not found: 1054 Unknown column '4' in 'field list'

If I output it as a raw sql query:

"select `4` from `projects`"

I am trying to add select() to it, to select everything from Project, but nothing works, what am I doing wrong?


Solution

  • You're going about it the wrong way.

    This:

    Task::where('assigned_id', auth()->user()->id)->whereNull('finished_at')->count()
    

    Will result in an int. In this case, I think it's 4, which gives you the error.

    I think you need to have the addSelect parameter be an array<string, Builder>. Try this:

    ->addSelect([
        'number_of_tasks' => Task::query()
            ->selectRaw('count(*)')
            ->where('assigned_id', auth()->user()->id)
            ->whereNull('finished_at');
    ])
    

    Also, you can eager load multiple relationships within the same with() call by passing in an array.

    return Project::query()
        ->with([
            'client',
            'status',
            'tasks',
            'tasks.user',
            'tasks.user.userAvatar',
        ])
        ->addSelect([
            'number_of_tasks' => Task::query()
                ->selectRaw('count(*)')
                ->where('assigned_id', auth()->user()->id)
                ->whereNull('finished_at'),
        ]);