我一直在努力找到一种重新设置Laravel 4中自动增量值的方法,但是似乎至少现在这个功能并没有嵌入到laravel 4中.
所以我这样做:
所以我这样做:
$user = User::find($user_id); if ($user) { if ($user->delete()){ DB::statement('ALTER TABLE users AUTO_INCREMENT = '.(count(User::all())+1).';'); echo json_encode('User Was Deleted Successfully..'); } }
像其他人一样回复,当你删除一行时,真的不需要把计数器移回去.然而,您可以截断一个将删除所有表行并重置计数器的表.
原文链接:https://www.f2er.com/laravel/130948.html您不能截断在其上应用了外键约束的表(截断与删除只删除所有行,同时保留自动递增计数器)不同.
因此,在使用外键约束时,MysqL可能会阻止您截断具有外键约束的表.
您可以执行以下步骤来实现您想要的,但请注意,可能存在数据完整性的风险.我只用它来进行测试.
>编辑DatabaseSeeder类(可在app / database / seeds / DatabaseSeeder.PHP获得),如下所示:
<?PHP class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Eloquent::unguard(); // Disable Foreign key check for this connection before running seeders DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $this->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;'); } }
>现在,Table Seeder类(在这种情况下的示例,UserTableSeeder应该在app / database / seeds / UserTableSeeder.PHP中创建)可以调用truncate table(s),如下所示:
<?PHP class UserTableSeeder extends Seeder { public function run() { // Truncate the table. DB::table('users')->truncate(); // The auto-increment has been reset. // Now we can start adding users. User::create( array( 'email' => 'example@domain.com','password' => Hash::make('test') ) ); } }