如何合并 laravel 中的两个 table 数据?
How to merge two table data in laravel?
我需要将所有用户数据集中在一个 blade,我有 table1
和 table2
。
表1
'id','name','phone','email','status','created_at'
table2
'id','name','mobile','email','status','created_at'
我尝试这样做,但不是预期的结果。
$usersTbl = DB::table('table1')->select('id','name','phone','email','status','created_at')->groupBy('phone')->paginate(20);
$ordersTbl = DB::table('table2')->select('id','name','mobile','email','status','created_at')->groupBy('mobile')->paginate(20);
$items=$ordersTbl->merge($usersTbl);
dd($items);exit;
您有分页,合并后需要重新计算分页。
需要使用unionAll然后分页:
$usersTbl = DB::table('table1')->select('id','name','phone','email','status','created_at')->groupBy('phone');
$ordersTbl = DB::table('table2')->select('id','name','mobile AS phone','email','status','created_at')->groupBy('phone');
$mergeTbl = $usersTbl->unionAll($ordersTbl);
DB::table(DB::raw("({$mergeTbl->toSql()}) AS mg"))->mergeBindings($mergeTbl)->paginate(20);
试试这个方法:
public function Details($id) {
/** Make an empty array **/
$patients = array();
/** Get Data from first model **/
$user_details = User::where(['id' => $id])->first();
/** Get Data from second model **/
$profile_details = Profile::where(['id' => $id])->first();
$patients[] = $user_details;
$patients[] = $profile_details;
}
return view('custom-view', compact('patients'));
}
我需要将所有用户数据集中在一个 blade,我有 table1
和 table2
。
表1
'id','name','phone','email','status','created_at'
table2
'id','name','mobile','email','status','created_at'
我尝试这样做,但不是预期的结果。
$usersTbl = DB::table('table1')->select('id','name','phone','email','status','created_at')->groupBy('phone')->paginate(20);
$ordersTbl = DB::table('table2')->select('id','name','mobile','email','status','created_at')->groupBy('mobile')->paginate(20);
$items=$ordersTbl->merge($usersTbl);
dd($items);exit;
您有分页,合并后需要重新计算分页。
需要使用unionAll然后分页:
$usersTbl = DB::table('table1')->select('id','name','phone','email','status','created_at')->groupBy('phone');
$ordersTbl = DB::table('table2')->select('id','name','mobile AS phone','email','status','created_at')->groupBy('phone');
$mergeTbl = $usersTbl->unionAll($ordersTbl);
DB::table(DB::raw("({$mergeTbl->toSql()}) AS mg"))->mergeBindings($mergeTbl)->paginate(20);
试试这个方法:
public function Details($id) {
/** Make an empty array **/
$patients = array();
/** Get Data from first model **/
$user_details = User::where(['id' => $id])->first();
/** Get Data from second model **/
$profile_details = Profile::where(['id' => $id])->first();
$patients[] = $user_details;
$patients[] = $profile_details;
}
return view('custom-view', compact('patients'));
}