detect-n-plus-one

检测 PHP 代码中的 N+1 查询问题。可发现循环中的查询、缺少预加载、滥用懒加载以及关联关系遍历问题。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "detect-n-plus-one":https://skillpi.com/zh/skills/deepskill-e402d887751ee15a147e700c0603ecd6cd9582d27757c31c1202d6ab928cabb9。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

检测 PHP 代码中的 N+1 查询问题。可发现循环中的查询、缺少预加载、滥用懒加载以及关联关系遍历问题。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
减记
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: detect-n-plus-one
description: Detects N+1 query problems in PHP code. Finds queries in loops, missing eager loading, lazy loading abuse, relationship traversal issues.

N+1 Query Detection

Analyze PHP code for N+1 query problems that cause excessive database queries.

Detection Patterns

1. Query Inside Loop

// N+1: Query for each user
$users = $userRepository->findAll();
foreach ($users as $user) {
    $orders = $orderRepository->findByUser($user); // Query per iteration
    // ...
}

// N+1: Doctrine lazy loading in loop
foreach ($users as $user) {
    foreach ($user->getOrders() as $order) { // Lazy loads per user
        echo $order->getTotal();
    }
}

2. Missing Eager Loading

// N+1: No JOIN/eager loading
$orders = $orderRepository->findAll();
foreach ($orders as $order) {
    echo $order->getCustomer()->getName(); // Lazy loads customer
    echo $order->getProduct()->getPrice(); // Lazy loads product
}

// FIXED: Eager load with DQL
$dql = "SELECT o, c, p FROM Order o
        JOIN o.customer c
        JOIN o.product p";

3. Relationship Traversal

// N+1: Multiple levels of lazy loading
foreach ($departments as $department) {
    foreach ($department->getEmployees() as $employee) { // N queries
        foreach ($employee->getProjects() as $project) { // N*M queries
            echo $project->getName();
        }
    }
}

4. Collection Methods in Loop

// N+1: count() triggers query each time
foreach ($categories as $category) {
    echo $category->getProducts()->count(); // Query per category
}

// N+1: filter() may not be optimized
foreach ($users as $user) {
    $activeOrders = $user->getOrders()->filter(
        fn($o) => $o->isActive()
    ); // May load all orders first
}

5. Eloquent N+1

// N+1: Laravel Eloquent
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->author->name; // Query per post
}

// FIXED: Eager loading
$posts = Post::with('author')->get();
$posts = Post::with(['author', 'comments.user'])->get();

6. API Calls in Loop

// N+1: External API pattern
foreach ($products as $product) {
    $price = $pricingApi->getPrice($product->getSku()); // API call per product
}

// FIXED: Batch API call
$skus = array_map(fn($p) => $p->getSku(), $products);
$prices = $pricingApi->getPrices($skus);

Grep Patterns

# Query methods inside foreach
Grep: "foreach.*\{[^}]*->find|foreach.*\{[^}]*->query|foreach.*\{[^}]*Repository" --glob "**/*.php"

# Getter calls that might lazy load
Grep: "foreach.*->get\w+\(\)" --glob "**/*.php"

# count() in loop
Grep: "foreach.*->count\(\)" --glob "**/*.php"

# Eloquent without with()
Grep: "::all\(\)|::get\(\)|::find\(" --glob "**/*.php"

Detection in Doctrine

// Check for LAZY fetch mode (default)
#[ManyToOne(fetch: 'LAZY')] // N+1 risk
private ?Customer $customer;

// Should use EAGER for frequently accessed
#[ManyToOne(fetch: 'EAGER')]
private ?Customer $customer;

// Or use DQL with JOIN
$qb->select('o', 'c')
   ->from(Order::class, 'o')
   ->join('o.customer', 'c');

Solutions

Eager Loading (Doctrine)

// DQL JOIN
$query = $em->createQuery(
    'SELECT u, o, p
     FROM User u
     LEFT JOIN u.orders o
     LEFT JOIN o.products p'
);

// Query Builder
$qb = $em->createQueryBuilder()
    ->select('u', 'o', 'p')
    ->from(User::class, 'u')
    ->leftJoin('u.orders', 'o')
    ->leftJoin('o.products', 'p');

Batch Loading

// Load all related entities at once
$userIds = array_map(fn($u) => $u->getId(), $users);
$orders = $orderRepository->findByUserIds($userIds);
$ordersByUser = [];
foreach ($orders as $order) {
    $ordersByUser[$order->getUserId()][] = $order;
}

foreach ($users as $user) {
    $userOrders = $ordersByUser[$user->getId()] ?? [];
}

Aggregation Instead of Counting

// Instead of N count queries
// SELECT COUNT(*) FROM products WHERE category_id = 1
// SELECT COUNT(*) FROM products WHERE category_id = 2
// ...

// Use single aggregation query
$counts = $em->createQuery(
    'SELECT c.id, COUNT(p) as cnt
     FROM Category c
     LEFT JOIN c.products p
     GROUP BY c.id'
)->getResult();

Severity Classification

Pattern Severity Queries
Query in loop (large dataset) 🔴 Critical O(n)
Nested relationship traversal 🔴 Critical O(n*m)
count() in loop 🟠 Major O(n)
Single lazy load 🟡 Minor +1

Output Format

### N+1 Query: [Description]

**Severity:** 🔴/🟠/🟡
**Location:** `file.php:line`
**Estimated Queries:** N + 1 (where N = number of items)

**Issue:**
[Description of the N+1 pattern]

**Code:**
```php
// Code with N+1 problem

Fix:

// With eager loading

Query Reduction: Before: 101 queries (1 + 100 items) After: 1-2 queries



## When This Is Acceptable

- **Small fixed collections** — Iterating over <5 items with individual queries may be simpler than eager loading
- **CLI/worker context** — Background jobs where latency is less critical than memory
- **Cached results** — Queries inside loops that hit cache (Redis/in-memory) instead of database

### False Positive Indicators
- Loop iterates over a constant or config-defined small set
- Query result is wrapped in cache decorator
- Code is in a console command or queue worker

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值78/100

亮点

  • 针对 PHP 开发中常见的 N+1 查询性能问题,提供检测模式、grep 模式、解决方案和严重性分类,具有明确的实用价值
  • 适用于 PHP 开发者优化数据库查询性能,属于明确场景的通用工具
触发精准65/100

待提升项

  • 触发词不全 原报告严重程度:轻微

    description 描述了 Skill 的功能,但未提供具体的触发词或命令示例,用户可能不清楚如何触发该 Skill

    改进建议:建议在 description 或 skill_body 开头添加具体的触发词或命令示例,例如 '检测 N+1 查询' 或 'analyze n+1'

结构规范92/100

亮点

  • 文档结构清晰,包含 Detection Patterns、Grep Patterns、Solutions、Severity Classification、Output Format、When This Is Acceptable 等章节
  • 提供了详细的代码示例和修复方案,frontmatter 完整,单文件未超过 500 行
执行可靠60/100

待提升项

  • 执行流程不明确 原报告严重程度:重大

    Skill 提供了多种检测模式和解决方案,但未明确说明如何实际执行检测(例如,是否需要用户提供代码文件路径,或者 Skill 如何访问代码),也未说明如何处理用户提供的代码或文件

    改进建议:建议在 skill_body 开头或 Detection Patterns 章节前添加 'How to Use' 或 'Usage' 章节,明确说明用户如何触发检测、提供代码或文件,以及 Skill 的输出格式

证据可验 (前四项均值)74/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。