0

WhereHas() In Laravel

 2 years ago
source link: https://dev.to/marcosgad/wherehas-in-laravel-1laa
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
WhereHas() In Laravel

Let's get started quickly
You may want to base your results on the existence of a relationship. For example, imagine that you want to retrieve all projects that have project_one starting with ,CSS. To do this, you can pass the name of the relationship to the whereHas() method and specify additional query constraints for has queries

Project::whereHas('project_one', function (Builder $query) {
    $query->where('title', 'like', 'CSS%');
})->get();
Enter fullscreen modeExit fullscreen mode

use with() method with WhereHas()

Project::with('project_one')->whereHas('project_one', function (Builder $query) {
       $query->where('title', 'like', 'CSS%');
})->get();
Enter fullscreen modeExit fullscreen mode

Now, Let's be more professional

public function scopeWithWhereHas($query, $relation, $constraint){
   return $query->whereHas($relation, $constraint)->with([$relation => $constraint]);
}
Enter fullscreen modeExit fullscreen mode
Project::withWhereHas('project_one', fn($query) =>
     $query->where('title', 'like', 'CSS%')
)->get();
Enter fullscreen modeExit fullscreen mode

Since this query builder may be needed in many Models in AppServiceProvider::boot()

use Illuminate\Database\Eloquent\Builder;
Builder::macro('withWhereHas', fn($relation, $constraint) =>
   $this->whereHas($relation, $constraint)->with([$relation => $constraint]);
);
Enter fullscreen modeExit fullscreen mode

I hope you enjoy the code.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK