내 Laravel App에서 설문 조사에는 많은 설문 조사 옵션이 있습니다. 나는 단순히 실행하여 이러한 옵션의 컬렉션을 만들 수 있습니다Laravel 모델 관계에서 키/값 쌍을 분리
$result = Poll::find(1)->options()->get();
이 쿼리 반환 : 내 설문 조사 옵션 내에서
Collection {#387 ▼
#items: array:6 [▼
0 => PollOption {#388 ▼
#table: "poll_options"
#connection: null
#primaryKey: "id"
#keyType: "int"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:8 [▼
"id" => 1
"poll_id" => 1
"option_text" => "Never"
"responses" => 54
"is_public" => 0
"created_at" => null
"updated_at" => null
"deleted_at" => null
]
#original: array:8 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▶]
#dates: []
#dateFormat: null
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
+wasRecentlyCreated: false
}
1 => PollOption {#389 ▶}
2 => PollOption {#390 ▶}
3 => PollOption {#391 ▶}
]
}
를, 정수를 반환 responses
라는 컬럼이있다. 위의 컬렉션을 가져와 responses
키/값 쌍을 분리해야합니다.
Collection {#385 ▼
#items: array:6 [▼
"responses" => 54
"responses" => 20
"responses" => 10
"responses" => 123
"responses" => 33
"responses" => 11
]
}
only()
수집 방법은 내가 필요 정확히, 그러나 나는 웅변 모델로 작업 할 때 쿼리를 구성하는 방법을 알아낼 수 없습니다 않습니다
$options = Poll::find(1)->options()->get();
$responses = $options->only('responses');
dd($responses->all());
는 responses
값 때문에 빈 컬렉션을 반환 PollOption
개체 내에 중첩되어 있습니다.
나는 flatten()
도 시도했지만이 시나리오에서는 아무런 영향을 미치지 않는 것으로 보입니다.
Eloquent 모델 컬렉션 내에서 단일 키/값 쌍을 반환하는 더 쉬운 방법이 있습니까?