P
P
prozrost2017-08-06 18:31:16
Laravel
prozrost, 2017-08-06 18:31:16

How to seed into a linked table?

I want (for training, the first application) Make a type of tournament table for various teams, there should be teams and matches between them. I want to understand how to do seeding in matches, seeding in teams has already been done like this:

<?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)
    ];
});

This is the factory and here is the run function itself:
public function run()
    {
        factory(App\Team::class,11)->create();
    }

According to my (probably not the best) assumptions, there should be two foreign keys in the match table (team1 and team2) and they should be related to Many-to-Many
. I implemented it like this:
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 also in the Team model:
public function matches()
    {
       return $this->belongsToMany('App\Match');
    }

There are two questions, have I built the structure correctly and how to seed into the matches table?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin B., 2017-08-06
@Kostik_1993

You need to use factor

factory(App\Category::class, 10)->create()->each(function ($c) {
        factory(App\Product::class, 25)->create()->each(function ($p) use ($c){
        	$p->categories()->attach($c);
                factory(App\Photo::class, rand(1, 3))->create()->each(function ($f) use ($p){
                    $f->product_id = $p->id;
                    $f->save();
                });
        });
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question