我有一個回傳以下結果的查詢。
Illuminate\Database\Eloquent\Collection {#5145
all: [
App\Models\Result {#5207
id: 198,
result_id: 30,
result_type: "App\Models\Touchpoint",
audit_id: 1,
weight: 7,
pics: 0,
recs: 0,
rating: 4,
comments: "none",
complete: 1,
created_at: "2022-06-03 03:42:24",updated_at: "2022-06-03 03:42:24",
result: App\Models\Touchpoint {#5210
id: 30,
name: "Lineman",
description: "The location food offer was available on Lineman",
sort_order: 25,
req_pics: 0,
req_recs: 0,
sector_id: 1,
created_at: null,
updated_at: "2022-04-02 14:02:34",
},
},
App\Models\Result {#5119
id: 199,
result_id: 29,
result_type: "App\Models\Touchpoint",
audit_id: 1,
weight: 7,
pics: 0,
recs: 0,
rating: 4,
comments: "none",
complete: 1,
created_at: "2022-06-03 03:43:38",
updated_at: "2022-06-03 03:43:38",
result: App\Models\Touchpoint {#5206
id: 29,
name: "Grab",
description: "The location food offer was available on Grab",
sort_order: 24,
req_pics: 0,
req_recs: 0,
sector_id: 1,
created_at: null,
updated_at: "2022-04-02 14:02:26",
},
},
],
}
這是我用來獲取該集合的查詢,我希望結果只包含這些結果中的 sort_order、名稱、描述、評級和權重,并將它們放在一個陣列中。我假設我需要使用 pluck 來獲取正確的欄位,但是當我嘗試 pluck 'result.name' 等時,我被告知結果不存在。
$result = Result::query()->where('audit_id', 1)->where('result_type', 'App\Models\Touchpoint')->whereIn('result_id', $tps)->with('result')->get();
這需要在查詢中而不操作集合,因為我需要將其輸入 Maatwebsite\Excel\Concerns\WithMultipleSheets,這需要查詢而不是查詢結果。
uj5u.com熱心網友回復:
您可以使用急切的負載約束
$result = Result::query()
->where('audit_id', 1)
->where('result_type', 'App\Models\Touchpoint')
->whereIn('result_id', $tps)
->with('result:id,sort_order,name,description')
->select('id', 'result_id', 'rating', 'weight')
->get();
如果要洗掉嵌套并展平結果集,則可以map()覆寫集合
$result->map(function($item) {
$item['sort_order'] = $item->result->sort_order;
$item['name'] = $item->result->name;
$item['description'] = $item->result->description;
//remove the nested relation
$item->unsetRelation('result');
})
->toArray();
/**
* Will return something like
[
[
'id' => 198,
'result_id' => 30,
'rating' => 4,
'weight' => 7,
'sort_order' => 25,
'name' => 'Lineman',
'description' => 'The location food offer was available on Lineman'
],
[
'id' => 199,
'result_id' => 29,
'rating' => 4,
'weight' => 7,
'sort_order' => 24,
'name' => 'Grab',
'description' => 'The location food offer was available on Grab'
]
]
*/
Laravel Docs - 雄辯的關系 - 約束急切的負載
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/485951.html
上一篇:Laravel如何進行范圍測驗
