[Chartjs]-Laravel query builder with conditions

2👍

Follow please Laravel:Collection:GroupBy

So it’s maybe you need to have a code look like this

$join = $this->tickets();
$tickets = $join
         ->when($category, function($query) use ($category) {
             $ranges = $this->dateRange($category);
             return $query->whereBetween('tickets.created_at', $ranges);
         })
         ->select(DB::raw('COUNT(tickets.id) as tickets'), 'ticket_status.name as name', 'tickets.created_at')
         ->get()->groupBy(/** YOUR LOGIC HERE  **/);

1👍

You’ll need to convert this to Laravel/Eloquent, but this is a raw db query that does what you’re looking for.

Assumed Tables / Data

Table: tbl_dates
id | date
1    2016-11-17 00:00:00
2    2016-11-18 00:00:00
...etc...

Table: tickets
id | created_at
1    2016-11-18 12:34:56
2    2016-11-18 01:23:45
3    2016-11-18 02:34:56

Table: ticket_status
ticket_id | name
1           Open
2           Closed
3           Closed

Query:

SELECT 
  COUNT(tickets.id) AS tickets,
  ticket_status.name, 
  DATE(tbl_dates.date) AS ticket_date
FROM 
  tbl_dates
LEFT JOIN 
  tickets 
ON
  (DATE(tbl_dates.date) = DATE(tickets.created_at))
LEFT JOIN
  ticket_status
ON
  (tickets.id = ticket_status.ticket_id)
GROUP BY 
  ticket_status.name
ORDER BY 
  ticket_date
ASC

Result:

 tickets | name | ticket_date
 0         NULL   2016-11-17
 1         Open   2016-11-18
 2         Closed 2016-11-18

Basically, to do this in pure MySQL you need a table with all dates. Check out this SO post for an easy way to generate the dates table.

1👍

Use MySQL’s date function to format the date first and then group by the formatted date:

So your query should look something like this:

$join = $this->tickets();
    $tickets = $join
            ->when($category, function($query) use ($category) {
                $ranges = $this->dateRange($category);
                return $query->whereBetween('tickets.created_at', $ranges);
            })
            ->select(DB::raw('COUNT(tickets.id) as tickets'), 'ticket_status.name as name', DB::raw('DATE('tickets.created_at') as created_date'))
            ->groupBy('ticket_status.name', 'created_date')
            ->get();

Leave a comment