有没有办法我可以使用雄辩或流利的laravel 4来截断数据库中的所有表格?我不想指定表名,我只想截断所有表。换句话说,清空所有表。
$tableNames = Schema::getConnection()->getDoctrineSchemaManager()->listTableNames();
foreach ($tableNames as $name) {
//if you don't want to truncate migrations
if ($name == 'migrations') {
continue;
}
DB::table($name)->truncate();
}
以下是基于@Hao Luo的答案。此外,它有这些优点:
这是代码:
DB::statement("SET foreign_key_checks=0");
$databaseName = DB::getDatabaseName();
$tables = DB::select("SELECT * FROM information_schema.tables WHERE table_schema = '$databaseName'");
foreach ($tables as $table) {
$name = $table->TABLE_NAME;
//if you don't want to truncate migrations
if ($name == 'migrations') {
continue;
}
DB::table($name)->truncate();
}
DB::statement("SET foreign_key_checks=1");
希望你喜欢! :)
在laravel 5中,migrate:fresh将删除数据库中的所有表(即使表与迁移无关)
这就是我如何截断数据库中的所有表(包括表异常),它适用于我。
// set tables don't want to trucate here
$excepts = ['migrations'];
$tables = DB::connection()
->getPdo()
->query("SHOW FULL TABLES")
->fetchAll();
$tableNames = [];
$keys = array_keys($tables[0]);
$keyName = $keys[0];
$keyType = $keys[1];
foreach ($tableNames as $name) {
//if you don't want to truncate migrations
if (in_array($name[$keyName], $excepts))
continue;
// truncate tables only
if('BASE TABLE' !== $name[$keyType])
continue;
\DB::table($name)->truncate();
}