【问题标题】:Get number of rows updated by Laravel DB Transaction获取 Laravel DB 事务更新的行数
【发布时间】:2015-01-10 13:43:46
【问题描述】:

我这样执行数据库事务:

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

当我执行DB::commit(); 并在我的回复中返回时,是否可以获得受影响/更新的行数?

编辑

$updates 包含 key = value 数组(其中 key 是列名)。

如果发生这样的更新:UPDATE some_table SET some_number = some_number WHERE id = 1 所产生的受影响行数将为0(即没有真正改变)。

但是,如果发生这样的更新:例如UPDATE some_table SET some_number = some_number + 1 WHERE id = 1,那么这将导致1 的受影响行数。

这是我试图在我的代码中确定的,一旦提交事务,是否真的更新了任何值。

【问题讨论】:

    标签: php database laravel-4 transactions


    【解决方案1】:

    只有当值与过去不同时才能更新:

    $count = DB::table('my_table')
      ->where('id', '=', $line_id)
      ->where($column_name, '!=', $new_value)
      ->count();
    

    通过这种方式,您可以判断给定行是否具有不同的值以及是否要更改它。

    查询前的count

    $number = DB::table('my_table')
      ->where('id', '=', $line_id)
      ->count();
    

    在响应中返回:

    return Response::make('Updated ' . $number, 200);
    

    【讨论】:

    • 我正在尝试确定在提交事务时是否更新了任何行 - 不计算表中的行数。我的更新查询对表进行了动态更新,即表上的任何列都可能已更新。
    • 我的问题得到了更新,更好地解释了我的目标。
    • 我认为您正在尝试获取ROW_COUNT() 的值。
    • 我认为如果你尝试更新与之前相同的列值的行,查询将被执行并且你不能说过去的值是否相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多