1

此查询需要选择名字或姓氏包含 $term 字符串的员工,但还要检查这些员工是否已分配给该职位,并仅返回那些未分配给该职位的员工。我正在使用一个employee_job 数据透视表。照原样,查询甚至返回那些已经分配给 jobid 并且在数据透视表中有记录的员工。

 $employees = 
    Employee::where(function($query) use ($term) {
                    $query->where('firstname', 'LIKE', '%' . $term . '%')
                          ->orWhere('lastname', 'LIKE', '%' . $term . '%'); })
              ->whereHas('jobs', function($query) use ($jobid) { $query->where('jobs.id','!=',$jobid); })
              ->take(5)->get();

我可以告诉错误是因为它不检查具有 jobid 的作业的计数是否为 0,而是返回具有 jobid 不匹配的任何其他工作的任何员工,即使他们有与 jobid 匹配的工作.

我需要这样的东西

$query->where('jobs.id',$jobid)->count() == 0; 
4

1 回答 1

1

您正在寻找whereDoesntHave(), 而不是whereHas():

$employees = Employee::where(function($query) use ($term) {
        $query->where('firstname', 'LIKE', '%' . $term . '%')
            ->orWhere('lastname', 'LIKE', '%' . $term . '%');
    })
    ->whereDoesntHave('jobs', function($query) use ($jobid) {
        $query->where('jobs.id', $jobid);
    })
    ->take(5)
    ->get();

这将返回没有与给定职位 ID 匹配的职位的员工。

于 2016-04-30T04:55:59.323 回答