DEV Community

mostafalaravel
mostafalaravel

Posted on

Why whereHas is very slow ?

Hello ,

let me fist show you a part of my code :

case 'first_name':
                        $eml = ($rule == 'or')
                            ? $eml->orWhereHas('user', function ($q) use ($condition) {
                                $q->where(
                                    'first_name','ilike','%bra%'
                                )->withTrashed();
                            })
                            : $eml->whereHas('user', function ($q) use ($condition) {
                                $q->where(
                                     'first_name','ilike','%bra%'
                                )->withTrashed();
                            });
                        break;
Enter fullscreen mode Exit fullscreen mode


`

The code above works but very slow , the sql output is using EXISTS :

time response 25 seconds !!!!

`

(...)
LEFT OUTER JOIN "work_regimes" 
ON              "wra1"."work_regime_id" = "work_regimes"."id" 
WHERE           EXISTS 
                ( 
                       SELECT * 
                       FROM   "users" 
                       WHERE  "emls"."user_id" = "users"."id" 
                       AND    "first_name"::text ilike ?) 
AND             "users"."is_activated" = ? 
AND             "emls"."deleted_at" IS NULL 
ORDER BY        "id" ASC
Enter fullscreen mode Exit fullscreen mode



When I replace
EXISTSbyIN` the response time is very very fast 0.3 second !

I replaced whereHas by wherIn but it's not working !

Top comments (2)

Collapse
 
stereobooster profile image
stereobooster

Post result of EXPLAIN your_query

Collapse
 
rogeliotrejo13 profile image
ROGELIO TREJO

Same issue, whereHas and Has with table with more than 15,000 rows, is too slowly query's spend 60-90 seconds.