-3

I would like to update record and check if not exists in table, but the problem is if I check exists, it worked but I cannot even update the one record that I selected because it already exist.

Here my code

$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";
}                         
});
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Questions that basically amount to "fix my code" need work. Please try to narrow your code down to a minimum complete verifiable example. – Athena Jul 08 '16 at 14:21

1 Answers1

0

Simple solution

Do not use exists, use first()

$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();
}

This assumes that you are only pulling one record... if not then just use for each to iterate over all of the records by replacing first with get.

geggleto
  • 2,605
  • 1
  • 15
  • 18