Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

Using Distinct and group by laravel Mysql

I have table requests with fields

`id` `user_id` `status` `url` `price` `date`

and table peoplewith fields

`id` `name` `number` `password` `nickname`

I am trying to group all requests by each date and count how many request is in each day with this query:

$data['dates'] = RequestModel::orderBy('date', 'desc')
        ->groupBy(DB::raw("DATE_FORMAT(date, '%Y-%m-%d')"))
        ->take(2)
        ->get(array(
            DB::raw('Date(date) as date'),
            DB::raw('COUNT(*) as requests'),
        ));

this gives data like this:

"dates": [
{
    "date": "2018-06-13",
    "requests": 230
},
{
    "date": "2018-06-12",
    "requests": 399
}]

The problem is that when user creates new request in people table is creating new user with same number and distinct nickname. like this:

`id` `name` `number` `password` `nickname`
 1   jack    555845   pass       555845-1
 2   jack    555845   pass       555845-2

I want to count requests with distinct user numbers and don't know how to do it. help me if you can

Upvotes: 4

Views: 6136

Answers (1)

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

I've found the solution

$data['requests'] = RequestModel::join(env('DB_DATABASE_2').'.people', env('DB_DATABASE_2').'.people.id', '=', env('DB_DATABASE_2').'.requests.user_id')
    ->where('requests.date', '>', \Carbon\Carbon::now('Asia/Tbilisi')->subDays(30))
    ->orderBy('requests.id', 'DESC')
    ->distinct()
    ->groupBy('people.number')
    ->get();

    $grouped = $data['requests']->groupBy(function($req){
        return explode(' ', $req->date)[0];
    });

    $data['dates'] = [];
    $i=0;
    foreach($grouped as $key => $date){
        $data['dates'][$i]['date'] = $key;
        $data['dates'][$i]['requests'] = sizeof($date);
        $i++;
    }

using laravel collection

Upvotes: 1

Related Questions