Rosti
Rosti

Reputation: 161

How to seed in relation table

I want to create some app like hockey teams ranks and matches. I think in matches table I must to have two foreign keys(first_team_id and second_team_id).I did it in migrations (create_mathes_table):

public function up()
    {
        Schema::create('matches', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('first_team_id');
            $table->unsignedInteger('second_team_id');
            $table->foreign('first_team_id')->references('id')->on('team');
            $table->foreign('second_team_id')->references('id')->on('team');
            $table->date('match_date');
        });
    }

and I have that relation in Team model(Many-To-Many):

public function matches()
    {
       return $this->belongsToMany('App\Match');
    }

And I already seeding in Team table but I don't know how to seed in relation table Match with two foreign keys,I seeded in Team table like this: Seeder:

public function run()
    {
        factory(App\Team::class,11)->create();
    }

Factory:

<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\Team::class, function (Faker\Generator $faker) {
    $team_example = ['Dinamo','Schacter','Zorya','Stal','Vorskla','Olimpik','Mariupol','Zvezda','Karpaty','Chernomorets','Veres'];
    return [
        'name' => $faker->unique()->randomElement($team_example),
        'score' => $faker->numberBetween($min = 1, $max = 15)
    ];
});

Upvotes: 1

Views: 100

Answers (1)

ImPerat0R_
ImPerat0R_

Reputation: 663

Define the factory for Match first.

$factory->define(App\Match::class, function (Faker\Generator $faker) {
    return [
        ///
    ];
});

And then try following:

factory(App\Match::class, 11)->create([
    'first_team_id' => factory(App\Team::class)->create()->id,
    'second_team_id' => factory(App\Team::class)->create()->id,
]);

Upvotes: 1

Related Questions