Laravel eloquent嵌套“WHERE NOT IN”加入查询

时间:2017-10-27 20:12:50

标签: php laravel laravel-eloquent nested-queries

我遇到了从SQL异常中编写适当的雄辩查询的问题。我的雄辩查询返回错误。 这是SQL异常:

SELECT * FROM `candidate_infos` 
JOIN training_infos on candidate_infos.id = training_infos.candi_id 
where candidate_infos.mdl_id=1
and candidate_infos.id not in ( (SELECT candi_id FROM training_infos WHERE 
candi_id in (1,5,6,8) ))

我试过了:

DB:: table('candidate_infos')
    ->join('training_infos','candidate_infos.id', '=', training_infos.candi_id')
    ->where('candidate_infos.mdl_id', $value->mdl_id)
    ->where('candidate_infos.id', 'not in', select(DB::raw("SELECT candi_id FROM training_infos WHERE candi_id in ($value->cadi_ids)")))
    ->get();

2 个答案:

答案 0 :(得分:0)

试试这个,

DB:: table('candidate_infos')
->join('training_infos','candidate_infos.id', '=', 'training_infos.candi_id')
->where('candidate_infos.mdl_id', $value->mdl_id)
->whereNotIn('candidate_infos.id', DB::raw("SELECT candi_id FROM training_infos WHERE candi_id in ($value->cadi_ids)"))
->get();

答案 1 :(得分:0)

你应该试试这个:

$resltQueries = DB::select(DB::raw("SELECT candi_id FROM training_infos WHERE candi_id in ($value->cadi_ids)"));
$arrQuery = array();

foreach($resltQueries as $key => $resltQuery){
  $arrQuery[$key] = $resltQuery;
}

DB:: table('candidate_infos')
  ->join('training_infos','candidate_infos.id', '=', 'training_infos.candi_id')
  ->where('candidate_infos.mdl_id', $value->mdl_id)
  ->whereNotIn('candidate_infos.id', $arrQuery)
  ->get();