table in database
table 1
----------
id name
----------
1 A
----------
2 B
----------
table 2
----------
id order
----------
1 burger
1 cake <---- I want to get the last data per ID
2 soda
2 coffee <-----
RESULT
----------
id name order
----------
1 A cake
2 b coffee
TEST
----------
1 A burger
1 A cake
2 b soda
2 b coffee
I want to display data in table like in "RESULT" but I'm getting error.. It display like in "TEST" pls help
testController.php
$disp = DB::table('table1') ->leftjoin('table2','table1.id','=','table2.id') ->select('table1.*','table2. *
')
->get();
return $disp;
Try
$res = DB::table('table2')->join('table1','table2.id','=','table1.id')->select('table1.name','table2.*')->get();
$result = $res->toArray();
$result = array_reverse($result);
$output = [];
foreach($result as $re)
{
// dd($re);
if(!array_key_exists($re->id,$output))
{
$output[$re->id] = [
'id' => $re->id,
'order' => $re->order,
'name' => $re->name
];
}
}
dd(array_reverse($output));
Output will be
[
0 => [
"id" => 1
"name" => "A"
"order" => "Cake"
]
1 => [
"id" => 2
"name" => "B"
"order" => "Coffee"
]
]
尝试像这样的 leftJoin() 函数。
DB::table('table1')->leftJoin('table2','table1.id','=','table2.id')->select(DB::raw('table1.*, table2.*'))->groupBy('table1.id')->get();
$disp = DB::table('table1')
->leftjoin('table2','table2.id','=','table1.id')-> groupBy('table1.name')->get();
return $disp;
使用内连接
DB::table('table1')->join('table2','table2.id','=','table1.id')->groupBy('table1.id')->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.