Красноречивый: получить данные за каждый день месяца - PullRequest
0 голосов
/ 13 января 2019

У меня проблемы с форматированием результатов запроса Eloquent.

У меня есть таблица Клубы, и она хранит футбольные клубы. Каждая запись в базе данных имеет значение «бренд», и теперь я хочу возвращать количество значений бренда в столбце за каждый день. Например: сегодня я добавил в таблицу 9 раз «Реал» и 40 раз «Барселона», поэтому ожидаю возвращаемое значение за каждый день в прошлом месяце, например:

[
    {
        "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 голосов
/ 13 января 2019

вы можете преобразовать данные следующим образом

$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;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...