mattkingshott / statistics
v2.0.0
2022-02-08 13:16 UTC
Requires
- php: ^8.0
- mattkingshott/triggers: ^1.0
Requires (Dev)
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.0
README
此包使Laravel应用能够维护数据库表的聚合统计信息。它是triggers包的配套包(并依赖于它)。
这是为谁准备的?
如果您正在运行需要执行多个记录的聚合操作(如COUNT
、SUM
、MIN
、MAX
或AVG
)的慢查询,那么这个包可能会对您有所帮助。这种情况通常出现在显示大量统计信息的仪表板上,例如:
SELECT (SELECT COUNT(*) FROM `articles`) AS 'articles', (SELECT COUNT(*) FROM `projects`) AS 'projects', (SELECT COUNT(*) FROM `tasks`) AS 'tasks'
相比之下,您可以配置该包在后台自动维护统计信息。因此,您可以使用以下方式代替慢查询(如上面的示例):
SELECT `table`, `values` FROM `statistics` WHERE `table` IN ('articles', 'projects', 'tasks')
或者,更好的做法是使用Eloquent模型查询数据
use Statistics\Models\Statistic; $stats = Statistic::query() ->whereIn('table', ['articles', 'projects', 'tasks']) ->get(['table', 'values']);
表 | 值 |
---|---|
文章 | { "count" : 6 } |
项目 | { "count" : 3 } |
任务 | { "count" : 2 } |
安装
使用Composer引入包
composer require caneara/statistics
配置
包包含一个配置文件,允许您更改包含聚合值的数据库表名(默认为'statistics')。如果您想更改它,请使用Artisan发布配置文件
php artisan vendor:publish
使用方法
该包会自动在您的数据库中注册和迁移一个statistics
表。然后,该表用作聚合值的存储库。值是通过数据库触发器维护的,这些触发器会在记录插入、更新或删除后自动触发。
在继续之前,重要的是要记住,数据库触发器(该包依赖于它)只能在创建表后添加到表中。换句话说,不要在通过
Schema::create
创建表之前尝试为表创建统计信息(这将在下面的示例中变得清楚)。
首先,将InteractsWithStatistics
特性添加到您想维护统计信息的任何Model
类中,例如:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Statistics\InteractsWithStatistics; class Article extends Model { use InteractsWithStatistics; }
接下来,在Model
上调用静态track
方法。
Article::track();
接下来,调用一个或多个可用的聚合方法
Article::track() ->count() // Count all records ->sum('likes') // Get the sum of all records using the 'likes' column ->average('likes') // Get the average value from the 'likes' column ->minimum('likes') // Get the smallest value in the 'likes' column ->maximum('likes'); // Get the largest value in the 'likes' column
如果您需要维护多个列的统计信息,可以多次调用聚合方法。只需提供自定义名称以区分它们即可
Article::track() ->count() ->sum('likes', 'sum_likes') ->sum('views', 'sum_views');
最后,调用create
方法来安装触发器。
Article::track() ->count() ->create();
示例
以下是一个在数据库迁移中的简单示例
class CreateArticlesTable extends Migration { public function up() : void { Schema::create('articles', function(Blueprint $table) { $table->unsignedTinyInteger('id'); $table->string('title'); }); Article::track() ->count() ->create(); } }
贡献
感谢您考虑为此包做出贡献。欢迎提交包含改进的PR,但如果它们是实质性的,请确保还包括测试或测试。
许可
MIT许可证(MIT)。请参阅许可证文件获取更多信息。