← 返回 Skill 列表
extension
分类: 开发与工程API Key 暂未确认

laravel:eloquent-relationships

定义清晰的关系并高效加载数据;防止N+1问题,安全地使用约束、计数/求和以及透视同步

person作者: jakexiaohubgithub

Eloquent Relationships and Loading

Model relationships express your domain; load only what you need.

Commands

# Typical loading
Post::with(['author', 'tags'])->withCount('comments')->paginate(20);

# Constrained eager loading
User::with(['posts' => fn($q) => $q->latest()->where('published', true)])->find($id);

# Pivot ops (many-to-many)
$post->tags()->sync([1,2,3]);       // atomic replace
$post->tags()->syncWithoutDetaching([4]);

# Chunking large reads
Order::where('status', 'open')->lazy()->each(fn($o) => ...);

Patterns

  • See laravel:performance-eager-loading for N+1 detection and measurement
  • Use whereHas() / has() to filter by related existence
  • Prefer withCount, withSum, withMax for simple aggregates
  • Apply global / local scopes for recurring constraints
  • Keep relationship names consistent and pluralized where appropriate
  • Laravel 13+: serialized Eloquent collections (e.g., in queued jobs) now restore eager-loaded relations after deserialization, matching single-model behavior — don't rely on relations being absent
  • Laravel 13+: model-level attributes like #[DateFormat('Y-m-d')] and #[WithoutTimestamps] are available (see laravel:php-attributes)