简体   繁体   中英

Laravel Eloquent ORM whereHas with a foreach loop

Here are the relationships:

A user has many skills, there is a join table user_skills. I need to search this table to return the profiles that have the particular skill. This is part of a bigger query that is being built, so that is why there is not a ->get() on here.

User Model

/**
 * A user may have many skills
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function skills()
{
    return $this->hasMany('App\Core\Platform\Models\UserSkill');
}

Below is the query that isn't doing what I need it to. I need it to return the users who have the particular skill, based on the ID being passed in the search (the $this->misc['search_skills'] value).

// Skills
$this->user = $this->user->whereHas('skills', function ($q)
{
     foreach ($this->misc['search_skills'] AS $skill)
     {           
          $q->orWhere('id', $skill);
     }
});

Any thoughts as to what I am doing wrong or how I could execute this in a different way?

$skills = $this->misc['search_skills']; // assuming this is an array
$this->user = $this->user->whereHas('skills', function ($q) use ($skills)
{
     $q->whereIn('id', $skills);
});

Any time you end up using orWhere multiple times on the same field, you should most likely be using whereIn.

Put the search skills into a variable ($skills), import that variable into your callback with use , then use whereIn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM