我一直在努力寻找一种在 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
它只是删除所有行keeping自动递增计数器。)。
因此,在使用时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' => '[email protected] /cdn-cgi/l/email-protection',
'password' => Hash::make('test')
)
);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)