Created
January 30, 2014 04:07
-
-
Save bgallagh3r/8702349 to your computer and use it in GitHub Desktop.
Disable Foreign Key Constraints when Seeding DB with Artisan Migrate/DB Seed This prevents SQL from throwing errors when you try to do DB::table()->truncate() as TRUNCATE is disallowed when FK constraints are in place.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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('UsersTableSeeder'); | |
// supposed to only apply to a single connection and reset it's self | |
// but I like to explicitly undo what I've done for clarity | |
DB::statement('SET FOREIGN_KEY_CHECKS=1;'); | |
} | |
} |
This is what i normally use for seeding when it comes to FK relationships
class CitySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Schema::disableForeignKeyConstraints();
DB::table('cities')->truncate();
factory(City::class, 10)->create();
Schema::enableForeignKeyConstraints();
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not working on Laravel 5.8.4 :(