我一直在努力寻找一种方法来重置 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..');
}
}
每次我从数据库中删除一个用户时,我都会将自动递增指针设置为所有用户的数量+1。
如果有人有更好的解决方案请告诉我..
最佳答案
就像其他人的回答一样,当你删除一行时,真的没有必要把计数器移回去。但是你可以 truncate
将删除所有表行并重置计数器的表。
你不能truncate
一个表有 Foreign Key Constraints
应用于它(truncate
与 delete
不同,它只是删除所有行,同时保持自动递增计数器。)。
因此,在使用 foreign key constrains
时, MySQL 可能会阻止您截断具有 foreign key constraints
的表应用于它。
您可以执行以下步骤来实现您想要的效果,但请注意,您的数据完整性可能存在风险。我只将它用于我的测试目的。
编辑
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
处创建)可以调用截断表,如下所示:<?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') ) ); } }
关于php - 如何重置 laravel 用户删除中的自动增量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546253/