在 laravel 11 应用程序中,用户模型已定义关系:
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
...
class User extends Authenticatable
{
public function uncompletedTasks(): belongsToMany
{
return $this->belongsToMany(Task::class)
->using(TaskUser::class)
->withPivot('supervisor_id') // Reference to "task_user" table
->where('completed', false)
->orderBy('priority', 'desc')
->orderBy('deadline_at', 'desc');
}
and when I need to get number of related data I do :
$this->uncompletedTasksCount = count($this->loggedUser->uncompletedTasks);
I check sql-tracement like:
SELECT `tasks`.*, `task_user`.`user_id` AS `pivot_user_id`, `task_user`.`task_id` AS `pivot_task_id`, `task_user`.`supervisor_id` AS `pivot_supervisor_id`
FROM `tasks`
INNER JOIN `task_user` on `tasks`.`id` = `task_user`.`task_id`
WHERE `task_user`.`user_id` = 1 AND `completed` = ''
ORDER BY `priority` desc, `deadline_at` desc
问题是如何更改我的请求以在 sql 请求中获取计数(不读取数据集合和 php“计数”方法)以减少流量?
据我理解你的问题,你可以做到
使用 withCount 方法
$userWithTaskCount = auth()->user()->withCount(['uncompletedTasks']);
这会将名为 uncompleted_tasks_count 的属性添加到您的用户模型中,您可以稍后访问该属性。
或
修改只需修改您的关系查询
如果您想直接在关系查询中包含计数,您可以修改 uncompletedTasks 方法。然而,
你不需要添加
selectRaw('count(*) as uncompleted_tasks_count')
直接在关系方法中,或者只需在需要时对关系使用 count() 这也是更好的方法 $count = auth()->user()->uncompletedTasks()->count();
请简单地这样做:
$this->uncompletedTasksCount = $this->loggedUser->uncompletedTasks()->count();