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

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?