Laravel 雄辩:获取每月每一天的数据

Laravel 雄辩:获取每月每一天的数据,laravel,eloquent,Laravel,Eloquent,我的雄辩的查询结果格式有一些问题 我有桌上俱乐部,它有足球俱乐部。数据库中的每个记录都有“brand”值,现在我想返回每天的列brand值计数。例如:我今天在我的表格中添加了9倍的“Real”和40倍的“Barcelona”,因此我期望上个月每天的回报值如下: [ { "date": "2019-01-12", "clubs": { "Barcelona": 40, "Real": 9 }

我的雄辩的查询结果格式有一些问题

我有桌上俱乐部,它有足球俱乐部。数据库中的每个记录都有“brand”值,现在我想返回每天的列brand值计数。例如:我今天在我的表格中添加了9倍的“Real”和40倍的“Barcelona”,因此我期望上个月每天的回报值如下:

[
    {
        "date": "2019-01-12",
        "clubs": {
             "Barcelona": 40,
             "Real": 9
        }
    }
] 
相反,我得到的是:

[
    {
        "date": "2019-01-12",
        "count": 9,
        "brand": "Real"
    },
    {
        "date": "2019-01-12",
        "count": 40,
        "brand": "Barcelona"
    }
]
这是我的控制器查询:

    $brandsMonthlyInfo = array();
    $dates = collect();

    foreach( range( -30, 0 ) AS $i ) {
        $date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
        $dates->put( $date, 0);
    }

    $countAddedBrands = DB::table('Clubs')->where([['created_at', '>=', $dates->keys()->first()]])
    ->groupBy( 'date' )
    ->groupBy( 'brand' )
    ->orderBy( 'date' )
    ->get( [
        DB::raw( 'DATE( created_at ) as date' ),
        DB::raw( 'COUNT(brand) AS "count"' ),
        'brand'
    ] );

    return $countAddedBrands;

你知道怎么解决吗?非常感谢您的帮助。

您可以这样转换数据

$brandsMonthlyInfo = array();
$dates = collect();

foreach( range( -30, 0 ) AS $i ) {
    $date = Carbon::now()->addDays( $i )->format( 'Y-m-d' );
    $dates->put( $date, 0);
}

$countAddedBrands = DB::table('Clubs')->where([['created_at', '>=', $dates->keys()->first()]])
->groupBy( 'date' )
->groupBy( 'brand' )
->orderBy( 'date' )
->get( [
    DB::raw( 'DATE( created_at ) as date' ),
    DB::raw( 'COUNT(brand) AS "count"' ),
    'brand'
] );

// create the array to contain the objects
$arrayOfAddedBrands = [];
foreach($countAddedBrands as $brand){
    $found = 0;
    // looping over the array to search for the date if it exists 
    foreach($arrayOfAddedBrands as $key => $brandFromArray ){
      // if the date exists
      if($brand->date == $brandFromArray->date){
          // add the brand to the clubs object
          $brandFromArray->clubs->{$brand->brand} = $brand->count;
          $found = 1;
          // assign the array element to the new modified object
          $arrayOfAddedBrands[$key] = $brandFromArray;
          break;
      }
    }
    // if the date not found
    if(!$found){
       // create new object and assign the date to it
       $brandObject = new \stdClass;
       $brandObject->date = $brand->date;
       // creating the clubs object
       $brandObject->clubs = new \stdClass;
       $brandObject->clubs->{$brand->brand} = $brand->count;
       // adding the final object to the array
       $arrayOfAddedBrands[] = $brandObject;
     }
 }

return $arrayOfAddedBrands;

使用SQL无法获得所需的结果。你需要用PHPThank来改造它,非常感谢你的Eslam。百万喜欢你。您在代码中的注释非常有用。@Morgan欢迎您,很乐意帮助:)。