1

I have a table like this:

User (user_id, count)

Now I want to insert a user id to this table, then update count = count + 1. How I can do this in eloquent?

I tried:

protected $table = 'user';


    public function insertAndUpdateCount($user_id)
    {
        return $this->insert($user_id)
                    ->increment('count', 1);
    }

But it's seem not working.

Tomato
  • 759
  • 2
  • 14
  • 26

2 Answers2

1

have you tried to use Increment & Decrement?

https://laravel.com/docs/5.8/queries#increment-and-decrement

Like this

DB::table('users')->increment('votes', 5);
1

I recommend you set the count column to autoincrement. Therefore, every time you insert a new row, the value automatically increases by 1. You can do this in a Laravel migration like this: $table->integer('count', true) Read more about Laravel Migrations here: https://laravel.com/docs/5.8/migrations

Out of curiosity: Why do you need a count column in the first place? If you just what to get the number of rows at some time, maybe it would be better to use SELECT COUNT() at this point. Because with a dedicated count column, you not only waste memory, but it also is prone to error, because if you delete a row, the count value of the other rows won't change.

mapawa
  • 179
  • 1
  • 4
  • 16