라라벨:속성별 컬렉션에서 개체 가져오기
Laravel에서 쿼리를 실행하면:
$foods = Food::where(...)->get();
...그리고나서$foods의 Illluminate 컬렉션입니다.Food모기기 ( 기기기기기기기기기 )
단, 이 어레이의 키는 다음과 같습니다.
[0, 1, 2, 3, ...]
를 들어 '아까부터'를Foodid경우 수 :24 、 24 、 개, 、 걸 of of :
$desired_object = $foods->get(24);
$desired_object->color = 'Green';
$desired_object->save();
할 뿐이며, ...이 할 수 없기 때문입니다.이것은 배열 내의 25번째 요소를 변경할 뿐이며, 이 요소가 있는 요소는 변경할 수 없기 때문입니다.id24달러입니다.
컬렉션에서 id / color / age 등 하나의 (또는 여러) 요소를 가져오려면 어떻게 해야 합니까?
물론 할 수 있습니다.
foreach ($foods as $food) {
if ($food->id == 24) {
$desired_object = $food;
break;
}
}
$desired_object->color = 'Green';
$desired_object->save();
하지만 그건 역겨워요
물론 할 수 있죠
$desired_object = Food::find(24);
$desired_object->color = 'Green';
$desired_object->save();
...하지만 이는 더 큰 의미가 있습니다. 왜냐하면 이미 원하는 오브젝트가 있는 경우 불필요한 쿼리를 추가로 수행하기 때문입니다.$foods★★★★★★ 。
안내 부탁드립니다.
편집:
확실히 하기 위해서,->find()다른 쿼리를 생성하지 않고 Illuminate Collection에서 사용할 수 있지만 기본 ID만 사용할 수 있습니다.예:
$foods = Food::all();
$desired_food = $foods->find(21); // Grab the food with an ID of 21
단, 다음과 같이 Collection의 Atribut에 의해 요소를 취득할 수 있는 깔끔한(루핑하지 않고 쿼리하지 않음) 방법은 아직 없습니다.
$foods = Food::all();
$green_foods = $foods->where('color', 'green'); // This won't work. :(
다음과 같이 사용할 수 있습니다.
$desired_object = $food->filter(function($item) {
return $item->id == 24;
})->first();
filter willA 환A 환A 환A 환 will will will will will will will will willCollection 1개밖에 것을 에, 「1」로 전화할 수 first 점에 있어서Collection.
필터가 필요 없게 되었습니다(혹은 이것이 4년 가까이 된 것인지도 모릅니다).다음과 같이 사용할 수 있습니다.
$desired_object = $food->first(function($item) {
return $item->id == 24;
});
은 라라벨이라는 합니다.keyBy모델에서 지정된 키를 기준으로 키를 설정할 수 있습니다.
$collection = $collection->keyBy('id');
이 컬렉션은 반환되지만 키는 다음 값입니다.id모든 모델에서 속성을 지정합니다.
그러면 다음과 같이 말할 수 있습니다.
$desired_food = $foods->get(21); // Grab the food with an ID of 21
필터 기능을 사용하는 번거로움 없이 올바른 아이템을 잡을 수 있습니다.
Laravel 5.5부터는 먼저 사용할 수 있습니다.장소()
고객님의 경우:
$green_foods = $foods->firstWhere('color', 'green');
내장된 수집 방법을 사용하여 (배열 키가 아닌) 프라이머리 ID로 검색합니다.예:
if ($model->collection->contains($primaryId)) {
var_dump($model->collection->find($primaryId);
}
contains()는 실제로 find()를 호출하고 늘을 체크하기 때문에 다음과 같이 줄일 수 있습니다.
if ($myModel = $model->collection->find($primaryId)) {
var_dump($myModel);
}
컬렉션 전체를 루프할 필요는 없기 때문에 도우미 기능은 이렇게 하는 것이 좋다고 생각합니다.
/**
* Check if there is a item in a collection by given key and value
* @param Illuminate\Support\Collection $collection collection in which search is to be made
* @param string $key name of key to be checked
* @param string $value value of key to be checkied
* @return boolean|object false if not found, object if it is found
*/
function findInCollection(Illuminate\Support\Collection $collection, $key, $value) {
foreach ($collection as $item) {
if (isset($item->$key) && $item->$key == $value) {
return $item;
}
}
return FALSE;
}
5이지만, .0는 Laravel 5.0 Collections를 하고 있습니다.where()이 목적을 위한 방법.
Laravel 5.0, 5.1 및 5.2의 경우where()의 메서드Collection동등한 비교만 할 수 있습니다.또, 엄밀한 대등 비교도 실시합니다(===디폴트로는) 입니다.대략적인 비교(==)에 합격할 수 있습니다.false세 번째 파라미터로 지정하거나whereLoose()방법.
Larabel 5.3 현재where()방법은 확장되어 보다 유사한 방식으로 기능하게 되었습니다.where()두 번째 매개 변수로 연산자를 받아들이는 쿼리 작성기의 메서드입니다.또한 쿼리 작성기와 마찬가지로 연산자는 아무것도 제공되지 않을 경우 기본적으로 동등한 비교가 됩니다.기본 비교도 기본 strict에서 기본 loose로 전환되었습니다.loose로 전환되었습니다.엄밀한 비교를 원하시면whereStrict()또는 그냥 사용하세요.===의 오퍼레이터로서where().
따라서 Larabel 5.0에서는 질문의 마지막 코드 예는 의도한 대로 작동합니다.
$foods = Food::all();
$green_foods = $foods->where('color', 'green'); // This will work. :)
// This will only work in Laravel 5.3+
$cheap_foods = $foods->where('price', '<', 5);
// Assuming "quantity" is an integer...
// This will not match any records in 5.0, 5.1, 5.2 due to the default strict comparison.
// This will match records just fine in 5.3+ due to the default loose comparison.
$dozen_foods = $foods->where('quantity', '12');
Kalley의 답변에 작지만 절대적으로 중요한 오류가 있음을 지적해야 합니다.나는 몇 시간 동안 이 문제와 씨름하다가 다음과 같은 사실을 깨달았다.
함수 내에서 반환되는 것은 비교이므로 다음과 같은 것이 더 정확합니다.
$desired_object = $food->filter(function($item) {
return ($item->id **==** 24);
})->first();
가치 발견을 위한 우아한 솔루션(http://betamode.de/2013/10/17/laravel-4-eloquent-check-if-there-is-a-model-with-certain-key-value-pair-in-a-collection/)을 채택할 수 있습니다.
$desired_object_key = $food->array_search(24, $food->lists('id'));
if ($desired_object_key !== false) {
$desired_object = $food[$desired_object_key];
}
위의 질문처럼 where 구를 사용할 때 결과를 얻으려면 get Or first 메서드를 사용해야 합니다.
/**
*Get all food
*
*/
$foods = Food::all();
/**
*Get green food
*
*/
$green_foods = Food::where('color', 'green')->get();
만약 당신이 라라벨에서 일대다 관계를 가지고 있다면, 당신은 간단히 다음과 같이 쓸 수 있다.
(예를 들어 자동차 제조업체 및 자동차 모델을 보유하고 있는 경우)
/** Initialize array */
$data = [];
/** Extract collection*/
foreach (Model::all() as $model) {
/** Initialize relation model array */
$relationObjects = [];
/** Iterate and make associative array */
foreach ($model->relationObjects as $relObject) {
$relationObjects[] = $relObject->name; // name or whatever property you want
}
/** Push 'relationObjects' to coresponding 'modelName' key */
$data[$model->name][] = $relationObjects;
}
그$data다음과 같은 형태로 표시됩니다.
[
"Porsche": [
[
"Cayenne",
"911 GT3"
]
],
"Ford": [
[
"Mustang"
]
],
]
언급URL : https://stackoverflow.com/questions/20931020/laravel-get-object-from-collection-by-attribute
'source' 카테고리의 다른 글
| .whl 파일이 있는 Python 패키지를 설치하려면 어떻게 해야 하나요? (0) | 2023.01.26 |
|---|---|
| MySQL 데이터베이스의 실제 크기를 얻는 방법 (0) | 2023.01.26 |
| Python에서 수동으로 예외 발생(던지기) (0) | 2023.01.26 |
| JUnit 테스트는 어떻게 하면 대기시킬 수 있나요? (0) | 2023.01.26 |
| 사전에서 키-값 쌍의 하위 집합을 추출하시겠습니까? (0) | 2023.01.26 |