ifnot/statistics

从 SQL 表中提取统计数据的工具

1.0 2018-03-13 15:35 UTC

This package is auto-updated.

Last update: 2024-08-28 17:06:13 UTC


README

允许您从一组带日期的 Eloquent 行中提取统计信息的 Illuminate\Support\Collection

特性

  • 基于 Carbon:易于日期管理,并易于与 Eloquent 集成
  • 简单的缓存:避免无用的重复数据库查询
  • 自定义间隔和步长:允许您更改日期(开始,结束)和步长(年度,月度,日度,时度)
  • 返回集合:返回 Illuminate\Support\Collection 以简化统计数据处理
  • 基于指标:以简单全面的方式查询统计数据

安装

使用 composer 安装

composer require ifnot/statistics

用法

1:从 eloquent 查询中实例化一个 Statistics 对象

use Ifnot\Statistics\Statistics;

// Get all validated sales (you can also take all with Sale::query())
$validSales = Sale::whereNotNull('validated_at');

// Put our sales into a Statistics object
$statistics = Statistics::of($validSales);

2:指定日期列和过滤数据的间隔

use Ifnot\Statistics\Interval;

// If we want to build statistics about validation date of sales (it can be also of the creation date, 
// in this case we will use the eloquent created_at ...) 
$statistics->date('validated_at');

// Set the interval, the params :
// 1 : the interval, check the constants Interval::$DAILY, Interval::$MONTHLY etc ... or use the string "daily", "monthly" instead
// 2 : the start date with carbon
// 3 : the end date with carbon
$statistics->interval(Interval::$DAILY, Carbon::createFromFormat('Y-m-d', '2016-01-01'), Carbon::now())

3:添加指标

// We want to count the sales with shipping and without shipping
$statistics->indicator('with_shipping', function($row) {
 return $row->shipping ? 1 : 0;
});
$statistics->indicator('without_shipping', function($row) {
 return $row->shipping ? 0 : 1;
});

// And count the sales with more than 500.00 € amount
$statistics->indicator('expensive_bough', function($row) {
 if($row->amount > 500.00) {
  return 1;
 } else {
  return 0;
 }
});

4:处理数据

$collection = $statistics->make();

// Use a foreach if you want to loop on each dates
foreach($collection as $date => $values) {
 echo $date ' : ' . $values->expensive_bough;
}

// Use Collection methods for statistics
$collection->sum('with_shipping'); // Count the shipping
$collection->avg('with_shipping'); // Average shpping sales on each days on the interval (if you selected daily)
$collection->min('with_shipping'); // Minimum daily shipping on the interval
$collection->max('with_shipping');

// etc ...

完整文档

... 这里进行工作