phpmysqllaraveleloquentexists

laravel eloquent ->whereHas - write your own exists( subquery )


Laravel Eloquent ->whereHas() uses anexists() subquery - https://dev.mysql.com/doc/refman/8.0/en/exists-and-not-exists-subqueries.html - in order to return your results.

I would like to write my own subquery, but I do not know how to tell Eloquent to ->where it.

If I do:

$query->where( DB::raw(' exists( subquery ) ')

Laravel instead writes the subquery as:

where exists( subquery ) is null

So I'm just wondering what $query->method() could be used to add an exists() subquery to the 'where' statements. The subquery would be just the same kind that laravel generates, but written out:

... and exists ( select * from `tbl` inner join `assets` on `custom_assets`.`id` = `tbl`.`asset_id` where `assets`.`deleted_at` is null and `users`.`id` = `assets`.`client_id` and `field_id` = ? and (`value` = ? and `assets`.`deleted_at` is null )

Solution

  • Use whereRaw():

    $query->whereRaw('exists( subquery )')