我目前正在使用我的show
功能UserController.php
来显示属于特定公司的所有用户。
/**
* Show the list of all users.
*
* @return Response
*/
public function show() {
$users = User::where('status',1)->with(['phones', 'companies'])->get(['id', 'first_name', 'last_name', 'email']);
$filteredUsers = [];
foreach($users as $user){
foreach($user->companies as $company){
if($company->id == session('selected_company')){
$filteredUsers[] = $user;
}
}
}
return view('users', ['team_members' => $filteredUsers]);
}
这工作得很好,但我想使用 Laravel 集合使代码更优雅,希望使用map()
,reject()
或reduce()
函数
我该怎么做?
我尝试了该reject()
功能,但它一直向我显示数据库中的所有用户。这是我尝试过的:
/**
* Show the list of all users.
*
* @return Response
*/
public function show() {
$users = User::where('status',1)->with(['phones','companies'])->get(['id', 'first_name', 'last_name', 'email']);
$userCollection = collect($users);
$filteredUsers = $userCollection->reject(function ($value) {
$userCompanies = collect($value->companies);
// if user companies contain the id, return that user
if($userCompanies->contains('id', session('selected_company'))){
return $value;
}
});
return view('users', ['team_members' => $filteredUsers->all()]);
}