How to reset auto increment in laravel user deletion?

前端 未结 4 635
北恋
北恋 2021-02-05 09:17

I have been struggling to find out a way to reset the auto increment value in Laravel 4 but it seems that this functionality is not embedded in laravel 4 at least for now. so i

4条回答
  •  情话喂你
    2021-02-05 10:05

    Like everyone else replied, there is not really a need to move the counter back when you delete a row. You can however truncate a table which will delete all the table rows and reset the counter.

    You cannot truncate a table that has Foreign Key Constraints applied on it (truncate is not the same as delete which simply deletes all the rows while keeping the auto-increment counter.).

    Hence, while using foreign key constrains, MySQL might stop you from truncating a table which has foreign key constraints applied to it.

    You can perform the following steps to achieve what you want, but beware, there may be a risk to your data integrity. I only use it for my testing purposes.

    1. Edit the DatabaseSeeder class (which is available at app/database/seeds/DatabaseSeeder.php) as follows:

      call('UserTableSeeder');
              // ...
      
              // FOREIGN_KEY_CHECKS is supposed to only apply to a single
              // connection and reset itself but I like to explicitly
              // undo what I've done for clarity
              DB::statement('SET FOREIGN_KEY_CHECKS=1;');
          }
      }
      
    2. Now the Table Seeder classes (Example, UserTableSeeder in this case, which should be created at app/database/seeds/UserTableSeeder.php) can call truncate table(s) as follows:

      truncate();
      
      
              // The auto-increment has been reset.
              // Now we can start adding users.
              User::create(
                  array(
                      'email' => 'example@domain.com',
                      'password' => Hash::make('test')
                  )
              );
          }
      }
      

提交回复
热议问题