[英]Laravel Eloquent ORM whereHas with a foreach loop
Here are the relationships:以下是关系:
A user has many skills, there is a join table user_skills.一个用户有很多技能,有一个连接表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.
这是正在构建的更大查询的一部分,这就是为什么这里没有 ->get() 的原因。
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).
我需要它根据在搜索中传递的 ID($this->misc['search_skills'] 值)返回具有特定技能的用户。
// 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?关于我做错了什么或如何以不同的方式执行此操作的任何想法?
$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.任何时候你最终在同一个字段上多次使用 orWhere 时,你很可能应该使用 whereIn。
Put the search skills into a variable ($skills), import that variable into your callback with use
, then use whereIn.将搜索技能放入变量 ($skills),
use
将该变量导入回调,然后使用 whereIn。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.