dsx5201
2017-01-05 17:28
浏览 271
已采纳

Laravel Eloquent ORM,其中有一个foreach循环

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?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duaeim2874 2017-01-05 17:40
    已采纳
    $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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题