caneara/statistics

此包已被废弃,不再维护。未建议替代包。

用于维护数据库记录统计信息的包

v2.0.0 2022-02-08 13:16 UTC

This package is auto-updated.

Last update: 2024-04-04 15:03:21 UTC


README

此包使Laravel应用能够维护数据库表的聚合统计信息。它是triggers的配套包(并依赖于它)。

这是为谁准备的?

如果你正在运行查询,因为它们需要对许多记录进行聚合(例如COUNTSUMMINMAXAVG)而变慢,那么你可能从这个包中受益。这种情况常见于显示大量统计信息的仪表板,例如。

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)。有关更多信息,请参阅许可证文件