带有内爆的Laravel查询



我有一个数组的值

Array
(
[0] => Python
[1] => PHP
[2] => MySQL
)

所以我想从表中搜索这三个项目使用query

$employees = DB::table('audit_employee_basics')
->select('audit_employee_basics.id as empid', 'emp_name', 'emp_code', 'designation_name', 'emp_company_email_id', 'emp_contact_number', 'emp_gender', 'emp_location'
, 'department_name', 'emp_joining_date', 'fk_emp_previous_exp', 'image')
->join('audit_department', 'audit_employee_basics.emp_fk_dep', '=', 'audit_department.id')
->join('audit_employee_skillset', 'audit_employee_skillset.fk_emp_id', '=', 'audit_employee_basics.id')
->join('audit_designation', 'audit_designation.id', '=', 'audit_employee_basics.emp_fk_des_id')
->where('primary_skill ', 'like', '%' .  implode("' OR primary_skill LIKE '%", $skill_name) .'%')
->distinct()
->get();

我试过where('primary_skill ', 'like', '%' . implode("' OR primary_skill LIKE '%", $skill_name) .'%')这对我不起作用。如有任何帮助,我将不胜感激。

→(‘primary_skill’,‘喜欢’,‘%’。内爆(";"或primary_skill像' %",skill_name美元)。' % ')

上一行是不正确的,因为你不能在一个where条件中注入多个where。QueryBuilder会将其作为字符串进行比较。

您可以使用regexp与从$skill_name数组创建的正则表达式匹配每个值

->where('primary_skill ', 'regexp', '(' .  implode("|", $skill_name) .')')

这将被编译为

where primary_skill regexp '(Python|PHP|MySQL)'

implode()不是在Eloquent/Laravel中构建这样的DB查询的方式。

应该是这样的:

...
->where(function($query) {
$query->where('primary_skill', 'like', '%Python%');
$query->orWhere('primary_skill', 'like', '%PHP%');
$query->orWhere('primary_skill', 'like', '%MySQL%');
})
...

当然,你需要使它动态,例如使用foreach。

...
->where(function($query) {
foreach(['Python', 'PHP', 'MySQL'] as $keyword) {
$query->orWhere('primary_skill', 'like', "%$keyword%");
}
})
...

可以通过foreach循环和->orWhere来实现。

$employees = DB::table('audit_employee_basics')
->select('audit_employee_basics.id as empid', 'emp_name', 'emp_code', 'designation_name', 'emp_company_email_id', 'emp_contact_number', 'emp_gender', 'emp_location'
, 'department_name', 'emp_joining_date', 'fk_emp_previous_exp', 'image')
->join('audit_department', 'audit_employee_basics.emp_fk_dep', '=', 'audit_department.id')
->join('audit_employee_skillset', 'audit_employee_skillset.fk_emp_id', '=', 'audit_employee_basics.id')
->join('audit_designation', 'audit_designation.id', '=', 'audit_employee_basics.emp_fk_des_id')
->where(function ($query) use ($book, $skills_array) {
foreach($skills_array as $skill_name) {
$query->orWhere('primary_skill', 'LIKE', '%' . $skill_name . '%');
}
})
->distinct()
->get();

其中$skills_array是你的数组。

最新更新