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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With