[英]Get results from Laravel by putting the results from the query into another query in foreach
我想通過將查詢的結果放入foreach的另一個查詢中來從Laravel獲取結果。
$first = DB::connection('store')
->table('entire_store')
->select('name', 'code', 'category', 'direct')
->where('open', 'Y')
->get();
第一個查詢獲取點的信息並將其處理為數組。
將分支機構的信息與員工表中的工作場所進行匹配。
我想一起保存員工的工作場所信息。
$temp = array();
$i =0;
foreach($first as $key => $item){
$temp[$i]['name'] = $item->name;
$temp[$i]['code'] = $item->code;
$temp[$i]['category'] = $item->category;
$temp[$i]['direct'] = $item→direct;
$second = DB::connection('store')
->table('entire_employer')
->SELECT('mgr_no','mgr_id', 'status')
->where('store',$item->code)->get();
//I tried.
foreach($second as $key2 => $item2){
$temp[$i]['mgr_id'] = $item2->mgr_id;
}
$i++;
}
我想將此查詢中的值存儲在temp_array中。
如果嘗試保存第二個查詢的值並打印temp_array()的值,則會出現錯誤。
我還需要檢查temp_array()嗎?
您要嘗試的是將entire_employer
表的LEFT JOIN entire_employer
到entire_store
表中。 這將完全按照您在代碼中的意圖進行操作:將一個表的記錄與另一個表的記錄進行匹配; LEFT entire_store
會將這些記錄錨定在主表中(在本例中為entire_store
)。
您可以在單個查詢中執行此操作,如下所示:
$data = DB::connection('store')
->table('entire_store')
->select(
'entire_store.name',
'entire_store.code',
'entire_store.category',
'entire_store.direct',
'entire_employer.mgr_no',
'entire_employer.mgr_id',
'entire_employer.status'
)
->leftJoin('entire_employer', 'entire_employer.store', '=', 'entire_store.id')
->where('entire_employer.open', 'Y')
->get();
您可以在此處閱讀有關聯接的更多信息: https : //www.sitepoint.com/understanding-sql-joins-mysql-database/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.