whereRelation
Pertimbangkan contoh ringkas ini:
ini mengambil semula semua
Post::whereRelation('comments', 'is_approved', true)->get();
mempunyai Post
ditetapkan ke comment
. is_approved
true
mari kita ilustrasikan dengan sistem penapisan kursus:
Kaedah pengawal ini menunjukkan cara membina penapis dinamik. SQL yang dihasilkan sangat cekap, mengendalikan keadaan hubungan dengan berkesan. Contohnya:
<?php namespace App\Http\Controllers; use App\Models\Course; use Illuminate\Http\Request; class CourseController extends Controller { public function browse(Request $request) { $courses = Course::query(); // Filter by instructor rating if ($request->has('top_rated')) { $courses->whereRelation('instructor', 'rating', '>=', 4.5); } // Filter by recent student reviews if ($request->has('well_reviewed')) { $courses->orWhereRelation('reviews', 'created_at', '>=', now()->subDays(30)); } // Filter by active discussion if ($request->has('active_discussion')) { $courses->whereRelation('discussions', 'last_activity', '>=', now()->subDays(7)); } return $courses->with(['instructor', 'reviews'])->latest()->paginate(); } }
Secara ringkas,
// Filters courses with: // - Highly rated instructors (4.5+) // - OR recent reviews (within the last 30 days) // - AND active discussions (within the last 7 days) $courses = Course::whereRelation('instructor', 'rating', '>=', 4.5) ->orWhereRelation('reviews', 'created_at', '>=', now()->subDays(30)) ->whereRelation('discussions', 'last_activity', '>=', now()->subDays(7)) ->get();
Atas ialah kandungan terperinci Pertanyaan hubungan fasih di laravel dengan whererelation. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!