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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献