0
在我的Laravel應用程序中,投票有許多投票選項。我可以簡單地運行時創建的這些選項的集合:從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模型集合中是否有更簡單的方法返回單個鍵/值對?