Russel
Russel

Reputation: 43

How to get Rows that falls in between dates and get their child Rows in another table - Laravel Eloquent

I want to create a single query that will fetch all Events that fall between dates. I also want to get all their child EventImages.

Can I get all of this into a single query?

Event Model

public function eventImages()
    
{
        
return $this->hasMany(EventImage::class, 'event_id');
    
}

Event Images Model

public function event()
    
{
        
return $this->belongsTo(Event::class);
    
}

Sample Query for getting Events between dates

$events = Event::whereBetween('date', [$start_date, $end_date])
            ->orderBy('date', 'ASC')
            ->get();

Thank you!

Upvotes: 2

Views: 38

Answers (1)

shaedrich
shaedrich

Reputation: 5715

You should already be able to access them. To make sure, their are included in serialization, you can eager load them via with().

Event::with(['eventImages'])
            ->whereBetween('date', [$start_date, $end_date])
            ->orderBy('date', 'ASC')
            ->get();

Upvotes: 1

Related Questions