If I'm understanding this correctly, You might be looking for the 'has' method. I'll try to explain it step by step though since it can look a bit confusing at first. First, you use the with
method to eager load your booths. This part is simple.
$clubs = Club::with('booths')->get();
This gets all clubs with the related booths. Now, the problem is that you want to limit the booths you retrieve. To achieve that, you can specify additional query constraints for eager loading queries. To do that, look at the example below. Also, link to docs on that: http://laravel.com/docs/5.1/eloquent-relationships#constraining-eager-loads
$clubs = Club::with(['booths' => function($query) {
// Additional query contraints
}])->get();
So, what kind of additional constraints do we want to add? Well, you just want to use the has
method. The has
method only retrieves the entries that "has" at least 1 related model. In other words, you want to retrieve the booths that have at least 1 event so you can do this:
$clubs = Club::with(['booths' => function($query) {
// Additional query contraints
$query->has('events');
}])->get();
Link to docs on the has
and whereHas
methods: http://laravel.com/docs/5.1/eloquent-relationships#querying-relations
That should get what you want.
Thanks for your reply - you're exactly right. I did in fact try this method but it didn't seem to be working.. because.... I only added the scope to the if statement, not the foreach!
if ( ! $club->booths()->hasEvents()->get()->isEmpty() )
{
foreach( $club->booths as $booth )
{
....
Whoops!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community