Shankar Akunuri
Shankar Akunuri

Reputation: 187

Laravel Eloquent Update Affected Rows count always 1

I am new to laravel. The problem I'm facing is,

When I tried to update a column in table with same data using laravel eloquent the affected rows gives me always 1.

Here it is the query running when I run update:

update `table` set `updating_column` = 1, `updated_at` = 2016-09-17 15:56:53;

In the above query laravel updating updated_at column along with the column i requested to update.

Thats why I am getting 1 row affected always.

Is there any way to get actual affected rows with out updated_at column.

EDIT:

$modelobj = new Model();
$aftcnt = $modelobj->where(['ssnid'=>Session::get('SSNID')])
                   ->update([updating_column'=>1]);

The variable $aftcnt gives me 1 when i refresh the page always.

Upvotes: 2

Views: 8095

Answers (3)

Marosdee Uma
Marosdee Uma

Reputation: 778

You need to add condition which row force to update by addding where condition

`updating_column` = 0;

like this

update `table` set `updating_column` = 1, `updated_at` = `2016-09-17 15:56:53` where `updating_column` = 0;

example

$modelobj = new Model();
$aftcnt = $modelobj->where(
              [
                'ssnid' => Session::get('SSNID'), 
                'updating_column' => 0
              ])
               ->update(['updating_column' => 1]);

Upvotes: 1

Majbah Habib
Majbah Habib

Reputation: 8558

For Laravel 5

You may see the example for getting affected row

$ids=[10,20,30,40];

$affectedRow=DB::update('update users set is_archive = 1, status=0 where id != ?', $ids);

echo $affectedRow;
exit;

Upvotes: 2

marcus.ramsden
marcus.ramsden

Reputation: 2633

As you already noted MySQL is reporting that there is 1 row affected because the row is "touched" meaning that the timestamps are updated. You can solve your problem in the following ways;

Run a query before you do the update:

$aftcnt = $modelobj->where('ssnid', Session::get('SSNID'))
    ->whereNot('updating_column', 1)->count();

Run update with touch disabled:

$modelobj->where(['ssnid'=>Session::get('SSNID')])
    ->update(['updating_column'=>1], ['touch' => false]);

When you disable the touch it won't try to change the timestamps.

Upvotes: 1

Related Questions