Flowframe / laravel-trend

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

Update how the date records are queried based on the start and end dates provided #31

Open 1jason1 opened 1 year ago

1jason1 commented 1 year ago

My appologies wasnt able to create a pull request.

This is just an update to Trend.php on how the date records are queried based on the start and end dates provided.

Originally if doing a count by month, day, or year the "start" and "end" dates are Carbon instances and would include the time in the query which was excluding some records. The solution I came up with is based on the aggregation which formats the Carbon instances to better align with the periods being queried. There may be another solution but this worked for me.

image

BuggerSee commented 10 months ago

Had the same issue and this fixed it for me.

jinbatsu commented 7 months ago

Had the same issue... thanks @1jason1 Here is if anyone to use it as own/custom Library to extend the Trend class.

<?php
namespace App\Lib;

use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

class Trend extends \Flowframe\Trend\Trend {

    public function queryDateFormat (Carbon $date): string | Carbon
    {
        return match ($this->interval) {
            'day', 'month', 'year' => $date->toDateString(), 
            default => $date,
        };
    }
    public function aggregate(string $column, string $aggregate): Collection
    {
        $values = $this->builder
            ->toBase()
            ->selectRaw("
                {$this->getSqlDate()} as {$this->dateAlias},
                {$aggregate}({$column}) as aggregate
            ")
            ->where(function ($q) {
                $q->whereBetween($this->dateColumn, [
                    $this->queryDateformat($this->start), 
                    $this->queryDateformat($this->end)
                ]);
            })
            ->groupBy($this->dateAlias)
            ->orderBy($this->dateAlias)
            ->get();

        return $this->mapValuesToDates($values);
    }

}
useahawk commented 2 weeks ago

I had the same issue with a date field retruning incorrect trend values. This fixed it for me and should be implemented.