我想在种子之前截断我的用户表。我这样做:
DatabaseSeeder.php:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder
{
public function run()
{
App\User::truncate();
factory(App\User::class,1)->create();
}
}
然后运行 php artisan db:seed
并出现错误:
In Connection.php line 664:
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constra
int (`mr_musicer`.`dislikes`, CONSTRAINT `dislikes_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `mr_musicer`
.`users` (`id`)) (SQL: truncate `users`)
In Connection.php line 458:
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constra
int (`mr_musicer`.`dislikes`, CONSTRAINT `dislikes_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `mr_musicer`
.`users` (`id`))
我现在想为什么我不能截断用户表!
答案 0 :(得分:1)
存在外键问题,表格正试图提醒您。 如果仍然要截断表。
Schema::disableForeignKeyConstraints();
// ... Some Truncate Query
Schema::enableForeignKeyConstraints();
别忘了使用:
use Illuminate\Support\Facades\Schema;
答案 1 :(得分:0)
您在其他一些表上都引用了您的用户。您应该将->onDelete('cascade')
添加到引用用户ID的“不喜欢”表列中,或者首先手动删除所有不喜欢的人。
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
答案 2 :(得分:0)
播种前截断数据的最简单方法
只需在 run 方法的开头添加这一行即可。
DB::table('users')->truncate();
run 方法的完整语法
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
class AdminSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('users')->truncate();
DB::table('users')->insert([
'name' => 'Admin',
'email' => 'admin@example.com',
'is_admin' => 1,
'password' => Hash::make('password'),
]);
}
}