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

时间:2019-01-12 22:42:45

标签: laravel eloquent

我的口才查询结果格式有些麻烦。

我有桌俱乐部,这里有足球俱乐部。数据库中的每个记录都有“品牌”价值,现在我想返回每天的列品牌价值计数。例如:我今天在表中添加了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;

您知道如何解决该问题吗?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您可以像这样转换数据

$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;