Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Model where relationship = id

Would love to know how other people are achieving the following?

Tables:

teams 
teams_users (pivot many teams, many users)
users

What i am trying to achieve

$teams->user->where('user_id', $id)->get();

however i am having to run a loop, and create another method on the team model to pluck(id, name)

// foreach ($teams as $team) {
//     # code...
//     dump($team->getUserIdsAttribute());
// }

Do you know a better way?

like image 983
Harry Bosh Avatar asked Sep 19 '25 16:09

Harry Bosh


1 Answers

If you are trying to get all teams with a specific a user id. Try

$teams = Team::with(['users' => function ($query) use ($id) {
    $query->where('id', '=', $id);
}])->get();

Or through the user

$user = User::with('teams')->find($id);

This is assuming you already defined the belongsToMany() relationship in each model.

like image 179
EddyTheDove Avatar answered Sep 22 '25 11:09

EddyTheDove