我想更新记录并检查表中是否不存在,但问题是如果我检查存在,它可以工作,但我甚至无法更新我选择的一条记录,因为它已经存在。
这是我的代码
$app->post('/update_function', function($request, $response, $args) {
$exists = $this->db->table('functions')->where('project_id', '=', $request->getParam('project_id'))
->where('function_number', '=', $request->getParam('function_number'))
->exists();
if(!$exists) {
$query = $this->db->table('functions')
->where('function_id', '=', $request->getParam('function_id'))
->update([
'project_id' => $request->getParam('project_id'),
'function_number' => $request->getParam('function_number'),
'function_text' => $request->getParam('function_text')
]);
if($query) {
echo "Function was updated";
}
}else {
echo "Can not update duplicate function number";
}
});
答案 0 :(得分:0)
简单的解决方案
不要使用exists,请先使用()
$record = $this->db->table('functions')
->where('project_id', '=', $request->getParam('project_id'))
->where('function_number', '=', $request->getParam('function_number'))
->first();
if (is_null($record)) { //record does not exist }
else {
$record->update([
'project_id' => $request->getParam('project_id'),
'function_number' => $request->getParam('function_number'),
'function_text' => $request->getParam('function_text')
]);
$record->save();
}
这假设您只拉一条记录......如果没有,那么只需使用每条记录,首先用get替换所有记录。