Laravel 的查询生成器以计算所有 25 至 35 岁的单身人士

Query Builder for Laravel to count all 25 to 35 years old that are single

这是我的 member_profiles table 的专栏:

编号
last_name
first_name
生日
civil_status

公民身份值为 "single"、"married" 和 "divorced"。

这个table已经有几千个条目了。 我想统计所有 25 到 27 岁的单身成员。

我可以从这样的东西开始,但不知道如何继续将它与特定的年龄段相匹配

$members = MemberProfile::where('civil_status', 'single')->count();

试试这个,

$count = DB::table('member_profiles')
         ->select(DB::raw('floor(DATEDIFF(CURDATE(),birthday) /365) as age') ,'civil_status')
         ->where('civil_status','single')
         ->where('age','>',25)
         ->where('age','<',35)
         ->count();

这里floor的功能是小数时四舍五入。由于 month_between 在 sql 中无法识别,您可以使用 DATEDIFF() 以天数为单位,然后将其除以 365 以获得年龄值。

希望,你明白了。

您可以使用碳和 whereBetween

  use Carbon\Carbon;
  Class {
  .......
  .......
  $today = Carbon::now();
  //$today = Carbon::createFromDate(2017, 7, 2);//to make manually
  $sub25 = $today->subYears(25);
  $today = Carbon::now();
  //$today = Carbon::createFromDate(2017, 7, 2);//to make manually
  $sub35 = $today->subYears(35);


  $members = MemberProfile::where('civil_status', 'single')
  ->whereBetween("birthday",[$sub25,$sub35])
  ->count();