Laravel/Eloquent:枢轴条件 table

Laravel/Eloquent: condition on a pivot table

我有 3 个 tables 'users'、'teams' 和 'teams_users'(一个枢轴 table)。主元 table 包含一个布尔字段 'kicked'。我没有找到获取用户未被踢出的团队列表的方法。我的代码如下所示:

$teams = Team::withCount('users')
               ->where($params)
               ->orderBy(DB::raw('users_count / max_members'), 'desc')
               ->orderBy('team_id', 'desc')
               ->has('users', '<', DB::raw('max_members'));

$user = app('auth')->user();
if (isset($user)) {
    // Here add the condition to exclude teams the user has been kicked from
}

首先,按照惯例,你的数据透视表应该命名为 team_user 并具有 team_id 和 user_id 列(当然它也可以有额外的)。

接下来,您应该在模型中设置关系(如果您还没有的话)。在您的用户模型中使用 belongsToMany() 关系来获取这样的团队

$user->teams

那么你可以简单地这样做

$user->teams()->where('kicked', false)->get()

有关关系的更多详细信息,请参见此处 https://laravel.com/docs/5.6/eloquent-relationships(请参阅多对多的枢轴 table)

挖掘文档,我发现了这个:

if (isset($user)) {
    $teams->whereDoesntHave('users', function ($query) use ($user) {
        $query->where("is_kicked", "=", '1')
              ->where('teams_users.user_id', '=', $user->id);
    });
}

它在 SQL 查询中生成 'NOT EXISTS' 条件。 完美运行!