I carry out DB transaction like this:
DB::beginTransaction();
try
{
foreach ($updates as $column_name => $new_value) {
DB::table('my_table')
->where('id', '=', $line_id)
->update(array($column_name => $new_value));
}
DB::commit();
return Response::make('Updated', 200);
}
catch (Exception $ex)
{
DB::rollback();
return Response::make('Error - '. $ex->getMessage(), 500);
}
Is it possible to get the number of rows affected/updated when I carry out the DB::commit();
and return it in my response?
EDIT
The $updates
contains key
= value
array (where the key
is the column name).
If an update like this occurs: UPDATE some_table SET some_number = some_number WHERE id = 1
the resulting affected row count will be 0
(ie nothing really changed).
However, if an update like this occurs: UPDATE some_table SET some_number = some_number + 1 WHERE id = 1
for example, then this will result in affected row count of 1
.
This is what I am trying to determine in my code, once the transaction is committed, has any values been really updated.
You could update only if the value is different from the past one:
$count = DB::table('my_table')
->where('id', '=', $line_id)
->where($column_name, '!=', $new_value)
->count();
In this way you can say if the given row has a different value and if you are going to change it.
A count
before the query:
$number = DB::table('my_table')
->where('id', '=', $line_id)
->count();
Return in the response:
return Response::make('Updated ' . $number, 200);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.