我正在尝试从表格中获取以下数据
我正在尝试按照脚本进行操作
$users = User::select(DB::raw('count(id) as agents, left(DATE(created_at),10) as registeredDate'))
->whereHas('roles', function($q){
$q->where('name', '=', 'agent');
})
->offset($start)
->limit($limit)
->orderBy($order,'DESC')
->groupBy('registeredDate')
->get();
上述查询返回每个日期的注册用户数
if($users){
foreach($users as $r){
$nestedData['agents'] = $r->agents;
$nestedData['date'] = date('d M Y',strtotime($r->registeredDate));
$data[] = $nestedData;
}
}
但是我想在同一查询中也获得用户详细信息。我想要的输出是
'data' => [
[
"agents" => "13",
"date" => "12 Jan 2019",
"nested_data" => [
[
'full_name' => 'john',
'status' => 'active',
'email' => 'john@gmail.com',
],
[
'full_name' => 'John',
'status' => 'active',
'email' => 'john2@gmail.com',
]
]
]
]
有人可以指导我如何实现它吗?我很感激。谢谢
答案 0 :(得分:0)
将查询更改为:
$users = User::select(DB::raw('count(id) as agents, left(DATE(created_at),10) as registeredDate'))
->whereHas('roles', function($q){
$q->where('name', '=', 'agent');
})
->offset($start)
->limit($limit)
->orderBy($order,'DESC')
->get();
将您的foreach循环更改为:
if($users){
foreach($users as $user){
$date = date('d M Y',strtotime($r->registeredDate));
$data[$date]['date'] = $date;
$data[$date]['nestedData'][] = ['first_name' => $user->first_name, 'status' => $user->status, 'email' => $user->email];
$data[$date]['agents'] = count($data[$date]['nestedData']);
}
}