【问题标题】:How to get index of element in Laravel collection如何获取 Laravel 集合中元素的索引
【发布时间】:2019-05-08 18:34:00
【问题描述】:

如何检索集合中元素的索引? 我的代码:

$users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();

if($users->contains(Auth::id())){
    //get the index of auth user id
 }

谢谢你的帮助

【问题讨论】:

    标签: php mysql laravel collections eloquent


    【解决方案1】:

    可以使用集合search()方法:https://laravel.com/docs/5.7/collections#method-search

    $users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();
    
    $userIndex = $users->search(function($user) {
        return $user->id === Auth::id();
    });
    

    请小心,因为索引可能为 0:

    // DON'T do this
    if($userIndex) {
        // this will get skipped if the user is the first one in the collection
    }
    
    // Do this instead
    if($userIndex !== false) {
        // this will work
    }
    

    【讨论】:

      【解决方案2】:
      $users = User::has('posts')->withCount('posts')->orderBy('posts_count')->take(50)->get();
      
      // this return a collection. So can do an if like this: $userIndex->count() > 0
      $userIndex = $users->filter(function($user) {
          return $user->id === Auth::id()
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-16
        • 2019-10-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-02
        • 2012-11-21
        • 2021-04-15
        • 1970-01-01
        相关资源
        最近更新 更多