mcpField
L
laravel-database-optimization

laravel-database-optimization

github.com/asyrafhussin数据与数据库951.1k 次安装9 周前更新
代码仓库

关于 laravel-database-optimization

面向 Laravel 13 应用的数据库优化参考技能,按 9 个类别整理 33 条规则,涵盖查询、索引、迁移与调试。

主要功能

  1. 019 类共 33 条规则
  2. 02Eloquent 与查询构造器建议
  3. 03索引与缓存实践
  4. 04大数据集处理
  5. 05迁移与查询调试

适用场景

  1. 01排查 N+1 查询
  2. 02为查询选择索引
  3. 03处理大型数据库表
  4. 04调查慢查询

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/asyrafhussin/agent-skills --skill laravel-database-optimization

安装后在 Claude Code 中输入/laravel-database-optimization确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

AGENTS.md
metadata.json
README.md
rules/
_sections.md
_template.md
cache-invalidation.md
cache-remember.md
cache-tags.md
cache-ttl.md
data-avoid-unbounded.md
data-chunk-by-id.md
data-cursor-iteration.md
data-cursor-pagination.md
debug-explain-analyze.md
debug-laravel-debugbar.md
debug-slow-query-log.md
eloquent-query-builder-hot-paths.md
eloquent-subquery-selects.md
eloquent-where-has-optimization.md
eloquent-with-count-aggregates.md
index-composite-indexes.md
index-covering-indexes.md
index-foreign-keys.md
index-full-text.md
lock-deadlock-retry.md
lock-pessimistic-locking.md
lock-short-transactions.md
migrate-concurrent-indexes.md
migrate-safe-column-additions.md
migrate-zero-downtime.md

详细介绍

Laravel 数据库优化

Laravel 13 应用的全面数据库优化指南。包含 9 个类别的 33 条规则,涵盖如何编写高性能数据库查询、正确建立索引、高效缓存、命名规范,以及如何在 Laravel 13 中调试慢查询。

元数据

  • 版本: 1.1.0
  • 框架: Laravel 13.x
  • PHP: 8.3+

适用场景

在以下情况下参考这些指南:

  • 编写 Eloquent 查询或使用查询构造器
  • 诊断并修复 N+1 查询问题
  • 在迁移中添加数据库索引
  • 实现 Redis 或基于缓存的优化
  • 对大型数据集进行分页或处理
  • 在数据库事务中封装操作
  • 为生产数据库创建或修改迁移
  • 使用 EXPLAIN 或 Laravel Debugbar 调试慢查询

按优先级划分的规则类别

优先级类别影响前缀
1查询性能与 N+1严重query-
2索引策略严重index-
3Eloquent 优化高eloquent-
4使用 Redis 缓存高cache-
5分页与大型数据集高data-
6事务与锁定高lock-
7迁移高migrate-
8查询调试中debug-
9命名与结构高naming-

快速参考

1. 查询性能与 N+1(严重)
  • query-eager-loading - 使用预加载消除 N+1 查询
  • query-prevent-lazy-loading - 在开发环境中阻止延迟加载
  • query-auto-eager-loading - 在模型上配置自动预加载
  • query-select-columns - 只选择需要的列,而非 SELECT *
2. 索引策略(严重)
  • index-foreign-keys - 为所有外键列建立索引
  • index-composite-indexes - 为多列查询创建复合索引
  • index-covering-indexes - 为读取密集型查询使用覆盖索引
  • index-full-text - 为搜索功能使用全文索引
3. Eloquent 优化(高)
  • eloquent-query-builder-hot-paths - 在性能关键路径中使用查询构造器
  • eloquent-with-count-aggregates - 使用 withCount 计数,而非加载关联
  • eloquent-subquery-selects - 使用子查询选择,避免额外查询
  • eloquent-where-has-optimization - 使用 whereIn 子查询优化 whereHas
4. 使用 Redis 缓存(高)
  • cache-remember - 使用 Cache::remember 缓存开销较大的查询
  • cache-invalidation - 在模型发生变化时使缓存失效
  • cache-tags - 使用缓存标签批量使缓存失效
  • cache-ttl - 为缓存数据设置合适的 TTL 值
5. 分页与大型数据集(高)
  • data-cursor-pagination - 为大型数据集使用游标分页
  • data-chunk-by-id - 使用 chunkById 处理大型数据集
  • data-cursor-iteration - 使用惰性游标进行内存高效的迭代
  • data-avoid-unbounded - 绝不要对大型表使用无界查询
6. 事务与锁定(高)
  • lock-short-transactions - 保持事务简短且专注
  • lock-deadlock-retry - 实现死锁重试逻辑
  • lock-pessimistic-locking - 对关键更新使用悲观锁定
7. 迁移(高)
  • migrate-zero-downtime - 编写零停机迁移
  • migrate-concurrent-indexes - 在生产环境中并发创建索引
  • migrate-safe-column-additions - 安全添加列,避免锁定表
8. 查询调试(中)
  • debug-explain-analyze - 使用 EXPLAIN ANALYZE 了解查询计划
  • debug-laravel-debugbar - 使用 Laravel Debugbar 查找查询瓶颈
  • debug-slow-query-log - 启用并监控慢查询日志
9. 命名与结构(高优先级)
  • naming-tables - 表命名约定(复数形式的 snake_case、数据透视表按字母顺序命名)
  • naming-columns - 列命名约定(外键、布尔值、时间戳、多态)
  • naming-relationships - 关系方法命名(单复数形式匹配)
  • naming-migrations - 迁移和索引命名约定

基本模式

在开发环境中禁止延迟加载
<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Model::preventLazyLoading(!app()->isProduction());
    }
}
使用 Redis 缓存开销较大的查询
<?php

use Illuminate\Support\Facades\Cache;

// Cache a query result for 1 hour (3600 seconds)
$popularPosts = Cache::remember('posts:popular', 3600, fn () =>
    Post::query()
        ->withCount('comments')
        ->orderByDesc('comments_count')
        ->take(10)
        ->get()
);
对大型数据集使用游标分页
<?php

// Cursor pagination — efficient for infinite scroll and large tables
$posts = Post::query()
    ->where('published_at', '<=', now())
    ->orderByDesc('published_at')
    ->cursorPaginate(15);
无需加载关联关系即可获取聚合计数
<?php

// Instead of loading all posts just to count them
$users = User::withCount('posts')->get();

foreach ($users as $user) {
    echo "{$user->name} has {$user->posts_count} posts";
}
使用 chunkById 处理大型数据集
<?php

// Memory-efficient processing of large tables
User::query()
    ->where('last_login_at', '<', now()->subYear())
    ->chunkById(1000, function ($users) {
        foreach ($users as $user) {
            $user->update(['status' => 'inactive']);
        }
    });
保持数据库事务简短
<?php

use Illuminate\Support\Facades\DB;

// Keep transactions short and focused
DB::transaction(function () {
    $order = Order::create([
        'user_id' => auth()->id(),
        'total' => $this->calculateTotal(),
    ]);

    $order->items()->createMany($this->cartItems());

    $order->user->decrement('credits', $order->total);
});

使用方法

阅读各条规则文件,了解详细说明和代码示例:

rules/query-eager-loading.md
rules/index-composite-indexes.md
rules/cache-remember.md
rules/_sections.md

每个规则文件都包含:

  • 带有元数据(标题、影响、标签)的 YAML frontmatter
  • 对规则重要性的简要说明
  • 附有说明的错误示例
  • 附有说明的正确示例
  • Laravel 13 和 PHP 8.3 的特定上下文及参考资料

参考资料

完整编译文档

如需查看包含所有展开规则的完整指南:AGENTS.md

评论

支持 Markdown