Search code examples
phpmysqldatabaselaravellaravel-seeding

Laravel database seeder, setting specific values laravel 5


I am trying to populate my databases and have a parent status table and a child server_statuses table. This is a one-to-many relationship.

The issue i'm running into is that the statuses table only has 3 values and they need to be set to specific values (success, warning, danger). Larvaels documentation doesn't go into much depth on how to accomplish this.

Im also not sure if the seeding is the reason im getting the error, posted below. If it isnt the seeding I was thinking I could possibly hand enter the 3 values within PHPmyAdmin then run my DB seeder. I will also post my migration as well as the seeder files.

Any thoughts on a solution to this error?

Current error when running the seeder:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constrai
ENCES `statuses` (`id`)) (SQL: insert into `server_statuses` (`server_id`, `status_id`, `updated_at`, `created_at`) values (20, 4, 2018-07-03 12:21:05,

Migrations:

 Schema::create('statuses', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('key');
            $table->string('status');
            $table->timestamps();
        });

 Schema::create('server_statuses', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('server_id')->unsigned();
            $table->foreign('server_id')->references('id')->on('servers')->onDelete('cascade');
            $table->integer('status_id')->unsigned();
            $table->foreign('status_id')->references('id')->on('statuses');
            $table->timestamps();
        });

Seeder factory(deletd what I was trying for the Status because it was a terrible attempt at a solution):

$factory->define(Status::class, function (Faker $faker) {

    return [
        'key' => ,
        'status' => 
    ];
});

$factory->define(ServerStatus::class, function (Faker $faker) {
    return [
        'server_id' => $faker->numberBetween($min = 1, $max = 20),
        'status_id' => $faker->numberBetween($min = 1, $max = 3)
    ];
});

Solution

  • This error is because you are inserting entries into server_statuses with status_id which not present in status table. First make entries in status with id 1 to 3 and then run command to insert data in server_statuses.

    Based on your last comment. The way to seed database from array.

    Create a seeder class:

    use Illuminate\Database\Seeder;
    use App\Models\Status;
    
    class StatusSeeder extends Seeder {
    
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run() {
            DB::table('status')->delete();
            $statuses = [
                ['key' => 1, 'status' => '1'],
                ['key' => 2, 'status' => '2'],
            ];
            foreach ($statuses as $status) {
                Status::create(array(
                    'key' => $status["key"],
                    'status' => $status["status"],
                ));
            }
        }
    
    }
    

    And add its entry in default DatabaseSeeder.php

    public function run()
        {
             $this->call(StatusSeeder::class);
        }
    

    Run the seeding process by php artisan db:seed. For more information, visit here.