Eloquent查询所有用户的数据透视表,还包括没有用户的记录


Eloquent Querying pivot table for all users - and also include records where there is no users

我正在查询一个表,该表查找分配给给定用户(登录用户)的所有任务。

我有一个任务/用户关系的透视表,因为一个任务可以分配多个用户。下面的函数也成功地获取了用户分配的所有任务。没有问题。

但是 ,我也想在下面的功能中包括没有用户被分配到的任务(在我的平台中,没有用户被指派到任务意味着它是为"每个人"分配的)。

$user_tasks = Team::currentTeam()->tasks()->with('user', 'comments')->whereHas('user', function($query) {
    $query->where('user_id', Auth::user()->id);
})->get();

也许应该这样做:

$user_tasks = Team::currentTeam()->tasks()->with('user', 'comments')->whereHas('user', function($query) {
    $query->where('user_id', Auth::user()->id);
})->doesntHave('user','or')->get();

因为没有函数或DoesntHave。只有:

public function doesntHave($relation, $boolean = 'and', Closure $callback = null)
{
    return $this->has($relation, '<', 1, $boolean, $callback);
}

定义,所以需要使用doesntHave并指定运算符作为第二个参数。

您可以单独获得未分配的任务:

$unassigned_tasks = Task::unassigned()->get(); // Uses a scope that says where user_id is null

然后类似于:

$user_tasks->tasks->push($unassigned_tasks);