关于 laravel-database-optimization
面向 Laravel 13 应用的数据库优化参考技能,按 9 个类别整理 33 条规则,涵盖查询、索引、迁移与调试。
主要功能
- 019 类共 33 条规则
- 02Eloquent 与查询构造器建议
- 03索引与缓存实践
- 04大数据集处理
- 05迁移与查询调试
适用场景
- 01排查 N+1 查询
- 02为查询选择索引
- 03处理大型数据库表
- 04调查慢查询
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ asyrafhussin/ agent-skills --skill laravel-database-optimization安装后在 Claude Code 中输入/laravel-database-optimization确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
AGENTS.mdmetadata.jsonREADME.mdrules/_sections.md_template.mdcache-invalidation.mdcache-remember.mdcache-tags.mdcache-ttl.mddata-avoid-unbounded.mddata-chunk-by-id.mddata-cursor-iteration.mddata-cursor-pagination.mddebug-explain-analyze.mddebug-laravel-debugbar.mddebug-slow-query-log.mdeloquent-query-builder-hot-paths.mdeloquent-subquery-selects.mdeloquent-where-has-optimization.mdeloquent-with-count-aggregates.mdindex-composite-indexes.mdindex-covering-indexes.mdindex-foreign-keys.mdindex-full-text.mdlock-deadlock-retry.mdlock-pessimistic-locking.mdlock-short-transactions.mdmigrate-concurrent-indexes.mdmigrate-safe-column-additions.mdmigrate-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- |
| 3 | Eloquent 优化 | 高 | 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