我有 3 個不同的表。
Table1是帶有主id鍵的“主”表。
Table2并Table3使用Table1id 作為外鍵table_1_id
假設我有來自表 1 的一些查詢:
Table1::where(...)->where(...)->get();
這給了我 100 個結果。
然后我想從 Table1 的 ID 中獲取所有資料Table2,Table3但仍然有 100 個結果,因此在將關系結果附加到原始模型結果時,類似于 Eloquents eager loading 的結構:
Array
(
[1] => Array
(
[table2_data] => Array ( <table2_rows_array that matches id1> )
[table3_data] => Array ( <table3_rows_array that matches id1> )
)
[2] => Array
(
[table2_data] => Array ( <table2_rows_array that matches id2> )
[table3_data] => Array ( <table3_rows_array that matches id2> )
)
...
...
[100] => Array
(
[table2_data] => Array ( <table2_rows_array that matches id100> )
[table3_data] => Array ( <table3_rows_array that matches id100> )
)
)
現在我正在做單獨的查詢,whereIn但它仍然不是相同的結構,我需要用 PHP 來操作它
uj5u.com熱心網友回復:
要渴望加載關系,您必須:
- 在這種情況下獲取基表資料
table1并為其創建一個集合 - 使用 table1 資料 ID 創建一個陣列
table1_id獲取關系列在 ids 陣列中的相關表- 遍歷第一個 table1 集合的每個元素,并為每個相關表添加一個屬性,相關資料作為值
table1_id等于當前元素id
$table1 = DB::table('table1')->select('*')->get();
$table1_ids = $table1->pluck('id')->all();
$table2 = DB::table('table1')->select('*')->whereIn('table1_id', $table1_ids)->get();
$table3 = DB::table('table1')->select('*')->whereIn('table1_id', $table1_ids)->get();
$table4 = DB::table('table1')->select('*')->whereIn('table1_id', $table1_ids)->get();
foreach($table1 as $el){
$el->table2data = $table2->where('table1_id',$el->id);
$el->table3data = $table3->where('table1_id',$el->id);
$el->table4data = $table4->where('table1_id',$el->id);
}
注意 :
- 對于 foreach,我們遍歷了一個集合,并使用了
where()的,collection所以沒有進行其他查詢!:D - 我們使用查詢獲取主模型,然后使用查詢獲取每個相關模型,而不是 N 1 查詢,在這種情況下,總共有4 個查詢,這與資料計數無關
the N
結果
一個包含所有 table1 資料的集合,在該集合的每個元素中,每個關系(table2_data、table3_data、table4_data..)與元素相關資料都有 3 個屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/535884.html
標籤:PHP数据库拉维
上一篇:將檔案的內容傳輸到集合
