我有一个获取表单详细信息的查询,如果已经分配给某个用户,则丢弃formid。
$formIds = DB::table('tbl_staff_user_details')
->select(DB::raw('GROUP_CONCAT(forms_assigned) as form_ids'))
->first();
$formIds = array_unique(explode(",", $formIds->form_ids));
if (Input::has('form_id'))
{
$sql = 'SELECT * from tbl_forms where id IN('.Input::get('form_id').')';
}
else
{
$lm_ids = Input::get('law_id');
$sql = 'SELECT *
FROM tbl_forms
WHERE lm_id IN('.$lm_ids.') AND id
NOT IN('.join(",",$formIds).')';
}
$data = DB::select($sql);
当我dd($formIds)
时,我得到" "
。
并出现错误:
语法错误或访问冲突:1064 在第3行(SQL:SELECT * FROM tbl_forms WHERE lm_id IN(1,2,3,4,5)AND id NOT IN())
如果$sql
为空,则如何触发$formIds
。
答案 0 :(得分:1)
您可以filter
空值:
$formIds = array_unique(explode(",", $formIds->form_ids));
$formIds = array_filter($formIds, function($item){
return !empty($item);
});
if (Input::has('form_id'))
{
$sql = 'SELECT * from tbl_forms where id IN('.Input::get('form_id').')';
}
else
{
$lm_ids = Input::get('law_id');
if(!empty($formIds)){
$sql = 'SELECT *
FROM tbl_forms
WHERE lm_id IN('.$lm_ids.') AND id
NOT IN('.join(",",$formIds).')';
}else{
$sql = 'SELECT *
FROM tbl_forms
WHERE lm_id IN('.$lm_ids.');
}
}
答案 1 :(得分:0)
如果$ formIds为null,如何触发$ sql。
编辑2:
如果
,我不希望AND id NOT IN('.join(",",$formIds).')
为$sql
$formIds
条款成为null
的一部分
...
if($formsIds) $formIds = array_unique(explode(",", $formIds->form_ids)); // Dont forget this line
if (Input::has('form_id'))
{
$sql = 'SELECT * from tbl_forms where id IN('.Input::get('form_id').')';
}
else
{
$lm_ids = Input::get('law_id');
if(is_null($formIds) || empty($formIds)) {
$sql = 'SELECT * FROM tbl_forms WHERE lm_id IN('.$lm_ids.')';
} else {
$sql = 'SELECT * FROM tbl_forms WHERE lm_id IN('.$lm_ids.') AND id NOT IN('.join(",",$formIds).')';
}
}
$data = DB::select($sql);
if($data) {
//Handle data here
} else {
//$data is empty
}
答案 2 :(得分:0)
在构建查询的行中,只有在有意义的情况下才添加NOT IN子句。
$sql = "SELECT *
FROM tbl_forms
WHERE lm_id IN('.$lm_ids.')";
if ($formIds != null) {
$sql .= ' AND id NOT IN('.join(",",$formIds).')';
}