Laravel's whereRelation
method simplifies filtering models based on their related data. This elegant solution replaces complex joins and subqueries with a cleaner, more maintainable syntax. It's particularly useful for building sophisticated filters in applications with interconnected models, such as e-commerce sites or content management systems.
Consider this concise example:
Post::whereRelation('comments', 'is_approved', true)->get();
This retrieves all Post
models where at least one associated comment
has is_approved
set to true
.
Let's illustrate with a course filtering system:
<?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(); } }
This controller method demonstrates how to build dynamic filters. The generated SQL is highly efficient, handling the relationship conditions effectively. For instance:
// 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();
In summary, whereRelation
offers a clear and expressive method for filtering models based on relationship attributes, resulting in cleaner, more maintainable Laravel applications.
The above is the detailed content of Eloquent Relationship Queries in Laravel with whereRelation. For more information, please follow other related articles on the PHP Chinese website!