英文:
Laravel addSelect
问题
我有一个查询,并尝试向其添加 addSelect()
,但不起作用,我不知道为什么,根据文档似乎是正确的。
查询:
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()
])
我得到这个错误:
列未找到:在'字段列表'中未知列 '4'
如果我将其输出为原始的 SQL 查询:
"select `4` from `projects`"
我尝试添加 select()
来选择 Project
中的所有内容,但什么都不起作用,我做错了什么?
英文:
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?
答案1
得分: 1
你这样做是错误的。
这个:
Task::where('assigned_id', auth()->user()->id)->whereNull('finished_at')->count()
会得到一个整数。在这种情况下,我认为是 4
,这会导致错误。
我认为你需要让 addSelect
参数成为一个 array<string, Builder>
。尝试这样做:
->addSelect([
'number_of_tasks' => Task::query()
->selectRaw('count(*)')
->where('assigned_id', auth()->user()->id)
->whereNull('finished_at');
])
另外,你可以在同一个 with()
调用中通过传递一个数组来预先加载多个关联。
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'),
]);
英文:
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'),
]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论