Laravel is a lot for many, choosing with Eloquent

I have 2 tables, users and skills, as well as many different relationships between them. The skill_user pivot table also has a column level - at what level does this user know this skill.

in user model I have:

public function skills(){ return $this->belongsToMany('Skill')->withPivot('level'); } 

and in the Skill model:

 public function users(){ return $this->belongsToMany('User'); } 

Now I need to run a query that will return something like this:

"Select all users who have skill_id_1> 40 && skill_id_2> 55 & skill_id_3> 67"

where skill_ids are different skills, and each returned user must have each of the given skills at the required level.

I searched the Laravel documentation and stackoverflow as much as I could, but couldn't find a solution. Any help would be appreciated, thanks!

+5
source share
1 answer

You need whereHas . A few of them.

 $users = User::whereHas('skills', function($q){ $q->where('skill_id', 1); $q->where('level', '>', 44); })->whereHas('skills', function($q){ $q->where('skill_id', 2); $q->where('level', '>', 55); })->whereHas('skills', function($q){ $q->where('skill_id', 3); $q->where('level', '>', 67); })->get(); 

I assume the values ​​are dynamic, so this should simplify it:

 $requirements = array('1' => 40, '2' => 55, '3' => 67); $users = User::query(); foreach($requirements as $id => $value){ $users->whereHas('skills', function($q) use ($id, $value){ $q->where('skill_id', $id); $q->where('level', '>', $value); }); } $users = $users->get(); 
+5
source

Source: https://habr.com/ru/post/1209983/


All Articles