Reputation: 3790
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?
Upvotes: 4
Views: 13047
Reputation: 907
Maybe you will like to do it in the more traditional way
use Illuminate\Database\Eloquent\Builder;
$team = Team::whereHas('user',function(Builder $query) use ($id){
$query->where( 'user_id' , $id );
})->get();
Upvotes: 2
Reputation: 13259
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.
Upvotes: 10