ethar's avatar
Level 5

whereRelation vs whereHas

i read about how use whereRelation, and i use it in my project, but in this code

        User::select('id','name')
            ->whereHas('Articles',function (Builder $query){
                $query->where('status',1)->orwhere(...)-whereBetween(..)->whereIn(...) ;
            })->get();
        }

how can replace whereHas and use whereRelation

0 likes
2 replies
MichalOravec's avatar
Level 75

You can't use whereRelation in your code.

This piece of code

$posts = Post::whereRelation('comments', 'is_approved', false)->get();

is equivalent to this one

$posts = Post::whereHas('comments', function ($query) {
    $query->where('is_approved', true);
})->get();

In your code there is more logic, which means you have to stay with whereHas.

1 like

Please or to participate in this conversation.