我想创建一些像曲棍球队排名和比赛的应用程序。我认为在匹配表中我必须有两个外键(first_team_id和second_team_id)。我在迁移中做了它(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');
});
}
我在团队模型(多对多)中有这种关系:
public function matches()
{
return $this->belongsToMany('App\Match');
}
我已经在Team表中播种但我不知道如何在关系表中播种与两个外键匹配,我在Team表中播种如下: 的播种机:
public function run()
{
factory(App\Team::class,11)->create();
}
工厂:
<?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)
];
});
答案 0 :(得分:1)
首先为Match
定义工厂。
$factory->define(App\Match::class, function (Faker\Generator $faker) {
return [
///
];
});
然后尝试以下:
factory(App\Match::class, 11)->create([
'first_team_id' => factory(App\Team::class)->create()->id,
'second_team_id' => factory(App\Team::class)->create()->id,
]);