How to only load n number of a relationship in Laravel?

Viewed 44

I am looking to fetch a list of companies and some but not all of their job listings. For instance on the "companies in Denver" page I'd like to show a company and the most recent jobs that are in Denver. I use tags to specify where a jobs location is, but could alternatively do a ilike on the job_listings.location field.

I'm using Laravel 8 with Postgresql and have a query to get all the job listings that match the given tag:

Company::whereIn('id', $companiesHiringInLocation->slice(0,15))
                ->with([
                    'jobListings' => function($query) use ($tag){
                        $query->withTagId($tag->id);
                    },
                    'jobListings.tags'
                ])
                ->get();

This works but some companies have thousands of job listings and I only need three job listings. This is how I'm rendering the list on the frontend currently:

@foreach($companies as $company)
    @foreach($company->jobListings as $index => $jobListing)
        @if($index > 2) @break @endif
        <div>{{ $jobListing->title }}</div>
    @endforeach
@endforeach

Is there a way I can modify or write a separate query to only get three job listings for each company? There will only be 10-15 companies on the list.

As an example, AngelList renders this on their page here where company may have many jobs but they only show a few:

enter image description here

I'm looking to grab the companies and three of their most recent (or any three really) job listings instead of querying for all of them. Is there a way to do this better with Eloquent or raw SQL?

1 Answers

you can use the take() method, for example:

$compaines = Company::with
(['jobs'=>function($q) {
$q->take(3);
}])->get();
Related