본문 바로가기
MySql

MySQL Laravel 컬렉션에서 요소의 인덱스를 얻는 방법

by 베이스 공부 2020. 10. 14.
반응형

컬렉션에서 요소의 인덱스를 검색하는 방법은 무엇입니까? 내 코드 :

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

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

도와 줘서 고마워

 

해결 방법

 


$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
}

 

참조 페이지 https://stackoverflow.com/questions/53661967

 

 

반응형

댓글