laravel-performance-eager-loading
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEager Loading and N+1 Prevention
预加载与N+1查询问题规避
Load Relations Explicitly
显式加载关联关系
php
Post::with(['author', 'comments'])->paginate();- Use /
load()after fetching models when neededloadMissing() - Select only required columns for both base query and relations
php
Post::with(['author', 'comments'])->paginate();- 在需要时,在获取模型后使用/
load()方法loadMissing() - 为基础查询和关联关系仅选择所需的列
Guard Against Lazy Loading in Dev/Test
在开发/测试环境中防范懒加载
Add to a service provider (non-production):
php
Model::preventLazyLoading(! app()->isProduction());添加到服务提供者(非生产环境):
php
Model::preventLazyLoading(! app()->isProduction());Verify
验证
- Use a query logger or debugbar to confirm relation queries are minimized
- Add tests that assert counts or avoid unexpected query spikes
- 使用查询日志或调试栏确认关联查询已被最小化
- 添加断言查询数量的测试,避免出现意外的查询峰值