我使用 laravel 创建 PHPunit 测试。对于每个测试,我需要“重置”数据库,但删除所有表并设置模式非常慢(在mysql上) - 所以我不想更改模式,而只删除数据并重置每个表的自动增量计数器。 p>
我如何使用播种机做到这一点?
最佳答案
因为我无法在网上轻松找到解决方案 - 所以经过我的研究,我创建了播种器,将其留在这里供后代使用;)
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class CleanTablesSeeder extends Seeder
{
public function run()
{
$rows = DB::select('SHOW TABLES');
$tables = array_column($rows, 'Tables_in_'.env('DB_DATABASE'));
$this->clean($tables);
}
private function clean($tables)
{
Model::unguard();
foreach ($tables as $table) {
DB::table($table)->delete();
DB::statement('ALTER TABLE '.$table.' AUTO_INCREMENT = 0;');
}
}
}
结果
我的数据库中有 22 个表(平均每个表 10 列),并且 5 个表只有很少的播种数据。对于在测试内调用 Artisan::call(...)
,时间如下:
17.83[s]
用于php artisan migrate:fresh --seed
5.56[s]
forphp artisan db:seed
(使用上面的 seder)
正如我们所见,播种器比从头开始设置模式快 3 倍以上 - 这为编写自动测试的开发人员提供了动力:)
关于Laravel 5.5 : chow to clean/drop db data (not schema! )并使用播种器重置自动增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48391053/