2

I have 3 tables 'users', 'teams' and 'teams_users' (a pivot table). The pivot table contains a boolean field 'kicked'. I didn't find the way to get the list of teams which the user has not been kicked from. My code looks like this:

$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
}
Angelo
  • 198
  • 1
  • 14
  • 1
    Possible duplicate of [Filtering pivot table data with Laravel models](https://stackoverflow.com/questions/20759891/filtering-pivot-table-data-with-laravel-models) – fubar Apr 09 '18 at 22:55

2 Answers2

6

Digging the documentation, I found this:

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

It generates a 'NOT EXISTS' condition in the SQL query. Works perfectly!

Angelo
  • 198
  • 1
  • 14
5

To start off, by convention your pivot should be named team_user and have team_id and user_id columns (it can have extras as well of course).

Next you should set up your relationships inside the models if you haven't yet. Use the belongsToMany() relationship inside your User model to be able to fetch teams like this

$user->teams

then you can simply do this

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

more detail on relationships here https://laravel.com/docs/5.6/eloquent-relationships (see Many to Many for pivot table)

Cârnăciov
  • 1,169
  • 1
  • 12
  • 24
  • Thank you, you put me on the right path. Actually, I used `$teams->whereDoesntHave('users', function ($query){});` which filters my query the way I want. – Angelo Apr 10 '18 at 11:05