I have a bookstore project, and have 2 table: publishers
and books
.
These is my two migrate file for books and publishers.
<?php
use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('available_quantity');
$table->string('isbn');
$table->string('language');
$table->integer('total_pages');
$table->float('price');
$table->string('book_image');
$table->string('description')->nullable();
$table->date('published_date');
$table->unsignedBigInteger('publisher_id');
$table->foreign('publisher_id')->references('id')->on('publishers');
$table->unique('isbn');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('publishers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->string('address');
$table->string('phone');
$table->string('description')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('publishers');
}
};
As you see, books
has a foreign key publisher_id
, which has reference to publishers
on id
, so when I run php artisan db:seed
,both tables will be seeded at the same time, but as we know, the publishers
table should be seeded before books
table be. So are there any way to seed tables orderly (not at the same time) ?
3
Answers
Well you can actually create the related publisher when creating the books in a seeder.
You can also directly define it in the
DatabaseFactoriesBookFactory::class
Eloquent Factories: Factory Relationship
Personally I prefer to make
Publisher
seeder first, then in set the value ofBook
‘spublisher_id
in the factory to be random from the existingPublisher
.Create 100
Publisher
, or any amount you wish to setRamdomly set
publisher_id
from the existing recordsYou have a file named DatabaseSeeder. You can choose the order of the seeder there:
If you put PublisherSeeder first, the seeder will be called before BookSeeder and you won’t have the constraint integretity error.