caneara / statistics
用于维护数据库记录统计信息的包
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)。有关更多信息,请参阅许可证文件。