[英]Laravel Raw Expressions
How do I write a Laravel raw expression that produces this results, I have year, gender and date of birth in my table and my main intention is to group by year as I group ages within ranges from 6-12, 13-17, 18-29... and also get gender count per age range. 我如何编写产生此结果的Laravel原始表达式,我在表中有年龄,性别和出生日期,并且我的主要目的是按年龄分组,因为我将年龄范围在6-12、13-17、18之间-29 ...并获得每个年龄段的性别计数。 My table looks like this.
我的桌子看起来像这样。
+------+--------+------------+
| year | gender | date_of_b |
+------+--------+------------+
| 2016 | male | 2004-05-01 |
| 2016 | male | 1990-02-09 |
| 2016 | male | 1960-04-14 |
| 2017 | female | 1975-03-08 |
| 2017 | male | 1994-07-19 |
| 2017 | female | 2005-03-15 |
| 2018 | male | 2010-05-30 |
| 2018 | female | 2000-04-11 |
| 2019 | male | 1988-06-15 |
| 2019 | female | 1980-08-10 |
| 2019 | male | 1990-03-18 |
+------+--------+------------+
This is the result I want 这是我想要的结果
{
2016: {
'6-12': {
male: 0,
female: 1
},
'13-17': {
male: 2,
female: 4
}
},
2017: {
'6-12': {
male: 10,
female: 12
},
'13-17': {
male: 21,
female: 24
}
}
}
You can do it via collection : 您可以通过集合来做到这一点:
User::get()->groupBy('year')->map(function($users){
return $users->groupBy('range')->map(function($users){
return $users->count();
});
});
DB::table('users')->groupBy('year')->get();
you can try this. 你可以试试看 And if this is not work show some related code.
如果这不起作用,请显示一些相关代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.