我有两个型号。 User
和Task
,它们具有多对多的关系。
在UserController中:
public function show(User $user)
{
return view('users.show', compact('user'));
}
用户/ show.blade.php:
Posts: @include('users.show.tasks', ['tasks'=>$user->tasks()]);
用户/显示/ tasks.blade.php:
Active Tasks Count: {{$tasks->active()->count()}}
查询:
select count(*) as aggregate from `tasks` inner join `user_task` on `tasks`.`id` = `user_task`.`task_id` where `user_task`.`user_id` = '1' and `status` = '4';
Pending Posts Count: {{$posts->pending()->count()}}
查询:
select count(*) as aggregate from `tasks` inner join `user_task` on `tasks`.`id` = `user_task`.`task_id` where `user_task`.`user_id` = '1' and `status` = '4' and `status` = '3';
这是用户模型中的任务方法
public function tasks()
{
return $this->belongsToMany(Task::class)->latest();
}
任务模型中的范围
public function scopeActive($query)
{
return $query->where('status', 4);
}
public function scopePending($query)
{
return $query->where('status', 3);
}
当我使用laravel-debugbar
检查查询时,对于第二个查询,结果包含两个状态ID,而不是一个