programing

웅변적인 ORM 레벨 5 ID 배열 가져오기

yoursource 2023. 1. 25. 08:56
반응형

웅변적인 ORM 레벨 5 ID 배열 가져오기

Allustic ORM larabel 5.1을 사용하고 있으며 0보다 큰 ID 배열을 반환하고 싶습니다.모델명은 다음과 같습니다.test.

시험해 본 결과:

$test=test::select('id')->where('id' ,'>' ,0)->get()->toarray();

다음과 같이 반환됩니다.

Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 ) )

그러나 다음과 같이 결과를 단순 배열로 작성해야 합니다.

Array ( 1,2 )

다음을 사용할 수 있습니다.

test::where('id' ,'>' ,0)->lists('id')->toArray();

메모: 모델을 정의하는 것이 좋습니다.Studly Case포맷, 예:Test.


다음 항목도 사용할 수 있습니다.

test::where('id' ,'>' ,0)->get('id');

갱신: (버전 > = 5.2의 경우 대신 'syslog()' 사용)

이 메서드는 새 버전에서 더 이상 사용되지 않습니다.>= 5.2대신 메서드를 사용할 수 있습니다.

test::where('id' ,'>' ,0)->pluck('id')->toArray();

메모: 예를 들어 블레이드에서 문자열이 필요한 경우 다음과 같이 toArray() 부분을 사용하지 않고 함수를 사용할 수 있습니다.

test::where('id' ,'>' ,0)->pluck('id');

로부터Collection, 다른 방법은 다음과 같습니다.

$collection->pluck('id')->toArray()

그러면 인덱스된 어레이가 반환되어 larabel에서 완벽하게 사용할 수 있습니다.whereIn()예를 들어 쿼리입니다.

그것에 대한 정답은 방법이에요.lists다음과 같이 매우 간단합니다.

$test=test::select('id')->where('id' ,'>' ,0)->lists('id');

안부 전해 주세요!

사용할 수 있습니다.all()대신 방법toArray()method (자세한 것은, laravel 메뉴얼을 참조해 주세요.

test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array

필요한 경우string, 를 사용하지 않고 사용할 수 있습니다.toArray()첨부 파일:

test::where('id' ,'>' ,0)->pluck('id'); //returns string

추가 정보(사용하시는 경우)DB:

DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();

또한 웅변 모델을 사용하는 경우:

test::where('id', '>', 0)->lists('id')->toArray();

lists() 메서드에 대해 읽어보십시오.

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()

컬렉션에서 모델 ID를 사용하여 배열을 가져오는 간단한 방법:

$test = test::select('id')->where('id' ,'>' ,0)->get('id')->modelKeys();

Larabel 5.5 이후 이용 가능: https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Collection.html#method_modelKeys

답변을 표시했지만, 이는 훨씬 더 간단한 접근법입니다.

App\User::pluck('id')->toArray()

라라벨 8에서 이건 나한테도 통한다.

$arr = SomeModel::where("field", value)->get()->toArray();

언급URL : https://stackoverflow.com/questions/34308169/eloquent-orm-laravel-5-get-array-of-ids

반응형