Reputation: 65
I have relationship between users and i want to search and get collection from connected users. Example:
Users:
ID: 1 | Nikola - he is TRAINER
ID: 2 | Test - he is his client
ClientTrainer Table:
trainer_id | client_id | status
1 | 2 | 1
When trainer search for specific users, i want to search only users who has status 1 and have relationship between them.
This is my current code:
if(isset($_GET['type'])){
$names = explode(" ", $_GET['type']);
$klijenti = User::where(function($query) use ($names) {
$query->whereIn('name', $names);
$query->orWhere(function($query) use ($names) {
$query->whereIn('surname', $names);
});
})->orderBy("last_seen","DESC")->get();
print_r($klijenti);
if(empty($_GET['type'])){
$klijenti = $user->allclients;
}
}
Upvotes: 0
Views: 274
Reputation: 1722
I don't know if I fully understand your requirement, but here is one solution that utilizes relationships:
Add this to your User
Model. This assumes that your "ClientTrainer" Table is called client_trainers.
public function clients()
{
return $this->belongsToMany('App\User', 'client_trainers', 'trainer_id', 'client_id')
->wherePivot('status', 1);
}
Option 1
Now you should be able to perform queries like this, assuming that Auth::user()
returns the currently logged in trainer:
$clients = Auth::user()->clients()->whereIn('name', $names)
->orWhereIn('surname', $names)
->orderBy("last_seen","DESC")->get();
Or to get all the clients of a single trainer just do something like
$clients = Auth::user()->clients()->get();
Option 2
If you want to search independently of a single trainer, you can do something like this:
$clients = User::has('clients')
->whereIn('name', $names)
->orWhereIn('surname', $names)
->orderBy("last_seen","DESC")->get();
The first part User::has('clients')
should only return Users that have at least on client with status = 1
in the client_trainers table.
Upvotes: 1