2

我目前正在使用我的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()]);
  }
4

1 回答 1

0

你不需要再次收集 $users,试试这样

$names = $users->reject(function ($user) {
return $user->active === false;
})
->map(function ($user) {
return $user->name;
});
于 2016-01-19T12:50:29.253 回答