PostgreSQL: Unique violation: 7 ERROR: duplicate key value violates unique constraint “users_pkey”

前端 未结 2 684
感情败类
感情败类 2021-01-31 10:15

I\'m using psql in my Laravel App. I\'m trying to create my user, and I keep getting this error

Unique violation: 7 ERROR: duplicate key value violates uniqu

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 10:49

    The following code provides a way to do this in Laravel which is what the OP is using.

    // Get all the tables from your database
    $tables = \DB::select('SELECT table_name FROM information_schema.tables WHERE table_schema = \'public\' ORDER BY table_name;'); 
    
    // Set the tables in the database you would like to ignore
    $ignores = array('admin_setting', 'model_has_permissions', 'model_has_roles', 'password_resets', 'role_has_permissions', 'sessions'); 
    
    //loop through the tables
    foreach ($tables as $table) { 
    
       // if the table is not to be ignored then:
       if (!in_array($table->table_name, $ignores)) { 
    
           //Get the max id from that table and add 1 to it
           $seq = \DB::table($table->table_name)->max('id') + 1; 
    
           // alter the sequence to now RESTART WITH the new sequence index from above        
           \DB::select('ALTER SEQUENCE ' . $table->table_name . '_id_seq RESTART WITH ' . $seq); 
    
        }
    
    }
    

    Note - Using ALTER SEQUENCE "blocks concurrent transactions". Consider using the SQL statement from alternative solution provided above if this is not desired.

提交回复
热议问题