php 我如何对Laravel收集使用reduce/reject/map功能?

jslywgbw  于 2022-12-25  发布在  PHP
关注(0)|答案(1)|浏览(117)

我目前正在使用UserController.php中的show函数来显示属于某个特定公司的所有用户。

/**
   * 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()]);
  }
bvjxkvbb

bvjxkvbb1#

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

$names = $users->reject(function ($user) {
return $user->active === false;
})
->map(function ($user) {
return $user->name;
});

相关问题