Flowframe / laravel-trend

Generate trends for your models. Easily generate charts or reports.
MIT License
590 stars 66 forks source link

grouped sets of trends #34

Open ceejayoz opened 1 year ago

ceejayoz commented 1 year ago

We have a need to group the trend by a particular column (for use in a stacked bar chart). I extended the class to permit a ->groupBy('type') on the Trend definition; the resulting trend is an array of trend data for each value of the type field. Is there any interest in working this up for inclusion in the package?

<?php

use Flowframe\Trend\Trend;
use Illuminate\Support\Collection;

class GroupedTrend extends Trend
{
    public string $groupColumn;

    public function groupBy(string $groupColumn): self
    {
        $this->groupColumn = $groupColumn;

        return $this;
    }

    public function aggregate(string $column, string $aggregate): Collection
    {
        $values = $this->builder
            ->toBase()
            ->selectRaw("
                {$this->getSqlDate()} as {$this->dateAlias},
                {$aggregate}({$column}) as aggregate,
                {$this->groupColumn} as group
            ")
            ->whereBetween($this->dateColumn, [$this->start, $this->end])
            ->groupBy($this->dateAlias, $this->groupColumn)
            ->orderBy($this->dateAlias)
            ->get();

        return $values->groupBy('group')
            ->map(fn($group) => $this->mapValuesToDates($group));
    }
}
Larsklopstra commented 1 year ago

Interesting, I might have an idea how to tackle this. Will look into it

vpuentem commented 2 months ago

up