Eloquent, Laravel'in ORM katmanıdır. Modeller arası ilişkileri metotlarla tanımlar; with() kullanıldığında N+1 sorgu sorunu yapısal olarak ortadan kalkar.
Tanımlama
<?php
class Blog extends Model
{
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
}
Eager loading
<?php
// KOTU: her blog icin ayri sorgu (N+1)
foreach (Blog::all() as $blog) {
echo $blog->author->name; // her seferinde sorgu
}
// IYI: tek sorguda join
$blogs = Blog::with('author', 'category')->get();
// Coklu iliski
$blogs = Blog::with(['author', 'comments' => fn($q) => $q->where('approved', true)])
->limit(20)
->get();
// Ilişkili sayim
$blogs = Blog::withCount('comments')->get();
echo $blogs[0]->comments_count;
Belirli sütunları çekmek
<?php
$blogs = Blog::with(['author:id,name,avatar'])->get();
// Tüm kullanıcı sütunlarını çekmeye gerek yok
Şartlı ilişki
<?php
$blogs = Blog::with(['comments' => function ($q) {
$q->where('created_at', '>=', now()->subDays(7))
->orderBy('created_at', 'desc')
->limit(3);
}])->get();
Yoksa ilişki
<?php
// category_id NULL ise hata yerine null doner
$blog->category?->name ?? 'Kategorisiz'
Birden fazla ilişki
<?php
class Product extends Model
{
public function images()
{
return $this->hasMany(Image::class);
}
}
// aracili (pivot) tablo
public function roles()
{
return $this->belongsToMany(Role::class, 'user_roles')
->withPivot(['created_at'])
->withTimestamps();
}
// kullanım
$user->roles()->attach($roleId);
$user->roles()->sync([1, 2, 3]);
Çoktan çoğla aracılı ilişki
<?php
class Student extends Model
{
public function courses()
{
return $this->belongsToMany(Course::class, 'enrollments')
->withPivot(['grade', 'enrolled_at'])
->withTimestamps()
->as('enrollment');
}
}
$student->courses()->attach($courseId, ['grade' => 85]);
Performans kontrolü
php artisan db:show
# N+1 tespiti
composer require barryvdh/laravel-debugbar
# ya da
php artisan db:monitor
Sonuç
Eloquent ilişkileri okunabilir sorgular yazmayı sağlar. Kritik kural şudur: listelerde mutlaka with kullanın; withCount ile sayaç ihtiyacını da tek sorguda karşılayın.
Arivo'da PHP scriptler, temalar ve eklentiler bulun. Kurulum desteği dahil.
Mağazaya Git