Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Truncate Table Befor Seeding

I want to truncate my user table befor seed.i do like this :

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();
     }
 }

Then run php artisan db:seed and have error:

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`))

I want to now why i can't truncate my user table!

like image 251
Omid Reza Heidari Avatar asked Mar 05 '23 05:03

Omid Reza Heidari


2 Answers

There is foreign key problem and table is trying to remind it to you. If you want to truncate table anyway.

    Schema::disableForeignKeyConstraints();

    // ... Some Truncate Query

    Schema::enableForeignKeyConstraints();

Don't forget To Use: use Illuminate\Support\Facades\Schema;

like image 175
Malkhazi Dartsmelidze Avatar answered Mar 12 '23 11:03

Malkhazi Dartsmelidze


Import DB:

use Illuminate\Support\Facades\DB;

And then use this piece of code to truncate the table:

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
DB::table('posts')->truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
like image 37
Mahsa Avatar answered Mar 12 '23 11:03

Mahsa