Shamik Roy
Shamik Roy

Reputation: 31

Laravel 5.2 Eloquent ORM to get data from 3 tables

I have the following tables. users, user_details and client_teams. Each user has one details and each user can have many teams. schema for users: id, name, email,parent_user_id user_details: id, user_id, client_team_id client_teams: id, user_id, team_name,status In user_model i have the following relations:

    public function userDetails(){
    return $this->belongsTo('App\Models\UserDetails','id','user_id');
    }

    public function clientTeamList(){
return $this->hasMany('App\Models\ClientTeams','user_id','id');
    }
In user_details model i have the following relation:
    public function clientMemberTeam(){
    return $this->belongsTo('App\Models\ClientTeams','client_team_id');
    }

I want to be show the list of users who have a specific team ID and created by a specific user. The query that i am using is this:

$userCollections=Users::where([
                        ['users.status','!=','DELETE'],
                        ['users.parent_user_id',$clientId],
                        ['users.id','!=',$loginUser->id]
                    ])
                    ->with([
                        'userDetails'=>function($query) {                           
                            $query->where('client_team_id',1); 
                        }
    
                    ]);

This is giving me all records for this user, Whereas i want to match by client_team_id and user_id

Upvotes: 0

Views: 36

Answers (1)

Boni
Boni

Reputation: 348

You need to use whereHas and orWhereHas methods to put "where" conditions on your has queries.

Please look into https://laravel.com/docs/8.x/eloquent-relationships

$userCollections = Users::where([['users.status', '!=', 'DELETE'], 
  ['users.parent_user_id', $clientId],['users.id', '!=', $loginUser->id]
  ])
  ->whereHas('userDetails' => function ($query) {
  $query->where('client_team_id', 1);
  })->get();

Upvotes: 1

Related Questions