Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gerardw85's avatar

Query Works - How to optimize it further.

Spoiler: Since I'm a beginning I assume the answer is, absolutely yes.

Tables Job_Types and Job_Type_Listing

Goal: A user is able to view a list of Job Types and click on them. However, I only want to display Job Types that actually have at least one listing.

   $jobtypes = DB::table('job_types')
                    ->join('job_type_listing', function($join) {
                        $join->on('job_types.id', '=', 'job_type_listing.job_type_id');
                    })
                    ->select('job_types.name','job_types.slug')
                    ->where('job_type_listing.job_type_id','>', 0)
                    ->groupBy('job_types.name','job_types.slug')
                    ->orderBy('job_types.name')
                    ->get();

Is there recommended reading for query optimization?

0 likes
2 replies
jlrdw's avatar

You might look at setting up eloquent relations and use eager loading, but that's just my suggestion.

Even without eloquent still consider related data via foreign keys and master detail setup (parent child).

1 like

Please or to participate in this conversation.