Support the ongoing development of Laravel.io →
posted 8 years ago
Eloquent
Last updated 1 year ago.
0

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#constrainin...

$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-re...

That should get what you want.

0

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!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

lainga9 lainga9 Joined 12 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.