Merge 'with' and 'whereHas' in Laravel 5

前端 未结 3 1928
清歌不尽
清歌不尽 2020-11-29 05:37

I have this code in Laravel 5, using Eloquent, which is working perfectly:

$filterTask = function($query) use ($id) {
    $query->where(\'taskid\', $id);
         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 05:50

    The 'macroable' way (Laravel 5.4+)

    Add this inside a service provider's boot() method.

    \Illuminate\Database\Eloquent\Builder\Eloquent::macro('withAndWhereHas', function($relation, $constraint){
        return $this->whereHas($relation, $constraint)->with([$relation => $constraint]);
    });
    

提交回复
热议问题