Giuseppe Liggieri
Giuseppe Liggieri

Reputation: 15

Column Increment value in laravel

i have a table like this:

key | counter | arrived |
123 |         |         |
121 |         |         |
313 |         |         |
543 |         |         |

and i need to feel the counter column with an incremental value, and arrived with "1", all like this:

key | counter | arrived |
723 |    1    |    1    |
421 |    2    |    1    |
313 |    3    |    1    |
543 |    4    |    1    |

i have all these key in an array, and my query is like this:

$update = DB::table('Selection')
        ->WhereIn('key', array_keys($req['aff']))
        ->update([
             'arrived' => 1
         ]);

in my array array_keys($req['aff']) i have all the key that i need to update, i am able to update the "arrived" column with "1"

but i don't know how to fill the counter column with the incremental value.

i tried this too but with no chance:

$update = DB::table('Selection')
            ->WhereIn('key', array_keys($req['aff']))
            ->update([
               'arrived' => 1,
               'counter' => DB::raw('counter+1')
            ]);

any suggest? Thank you in advance and merry xmas :D

Upvotes: 1

Views: 481

Answers (1)

Jignesh Joisar
Jignesh Joisar

Reputation: 15115

you need to use mysql IFNULL method here because if your value is null then not increment value so if value is null then set default value is zero

\DB::table('Selection')
            ->whereIn('key', array_keys($req['aff']))
            ->update([
               'arrived' => 1,
               'counter' => \DB::raw('IFNULL(counter,0) + 1')
            ]);

for more information read this question see

note mysql datatype must be int and also set default value is zero

in sql server used ISNULL function used like that

\DB::table('Selection')
                ->whereIn('key', array_keys($req['aff']))
                ->update([
                   'arrived' => 1,
                   'counter' => \DB::raw('ISNULL(counter,0) + 1')
                ]);

for more information read this article

Upvotes: 1

Related Questions