如何在Query builder laravel中执行此SQL

时间:2017-04-30 14:43:11

标签: sql laravel query-builder laravel-query-builder

如何在“查询构建器层级”

中执行此SQL
select Doctor_id from doctors where Doctor_id NOT IN
 (SELECT Doctor_id from report_reviewers WHERE Report_id = 26 )

1 个答案:

答案 0 :(得分:1)

试试这个

$result = DB::table('doctors')
->whereNotIn('doctor_id', function($q){
    $q->from('report_reviewers')
    ->select('Doctor_id')
    ->where('Report_id', '=', 26)
})
->select('doctor_id')
->get();

如果您有疑问,如果您知道原始SQL,则只需执行

即可
$query = 'select Doctor_id from doctors ...';
$result = DB::select($query);

此外,所有功劳归于这个天才How to create a subquery using Laravel Eloquent?

<强>更新

缺少的参数来自您正在使用的闭包

->whereNotIn('doctor_id', function($q,$id){ 
    $q->from('report_reviewers') 
    ->select('Doctor_id') 
    ->where('Report_id',$id); 
}) 

您需要像这样传递$id变量

->whereNotIn('doctor_id', function($q) use ($id) { 
    $q->from('report_reviewers') 
    ->select('Doctor_id') 
    ->where('Report_id',$id); 
}) 

再试一次,看看。