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.

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

报告相同问题?

悬赏问题

  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了