Question: Laravel Eloquent ORM whereHas with a foreach loop

Question

Laravel Eloquent ORM whereHas with a foreach loop

Answers 1
Added at 2017-01-05 18:01
Tags
Question

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?

Answers to

Laravel Eloquent ORM whereHas with a foreach loop

nr: #1 dodano: 2017-01-05 18:01
$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), important that variable into your callback with use, then use whereIn.

Source Show
◀ Wstecz