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

JackJones's avatar

Is there any way to optimize this query?

Can this query be optimized? It seems to be too complicated, Laravel always seems to have a more elegant answer

        $category = $category->load(['products' => function ($query) {
            $query->with(['features' => function ($x) {
                $x->with('field')
                    ->whereHas('field', function($y) {
                        $y->where('show_list', 1);
                    });
            }])
                ->whereHas('features', function ($query) {
                    $query->where('value_number', 2);
                });}]);
0 likes
1 reply
tisuchi's avatar

I think you can rewrite by using . (dot notation).

$category = $category->load(['products' => function($query){
                $query->whereHas('features.field.show_list', 1);
            }])->whereHas('features.value_number', 2);

Note: The code has not been checked.

Please or to participate in this conversation.