【问题标题】:How to seed in relation table如何在关系表中播种
【发布时间】:2017-08-07 14:29:10
【问题描述】:

我想创建一些应用程序,例如曲棍球队排名和比赛。我认为在匹配表中我必须有两个外键(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)
    ];
});

【问题讨论】:

  • 什么是锦标赛类型?是淘汰赛还是联赛类型?
  • 你能把Match的模型工厂也展示一下吗?
  • 我无法为 Match 模型建立工厂,这是个问题

标签: php laravel laravel-5


【解决方案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,
]);

【讨论】:

  • 我试过你的答案,但现在我在做“artisan db:seed”时出现溢出异常
  • 哪个溢出异常。
猜你喜欢
  • 1970-01-01
  • 2016-05-28
  • 1970-01-01
  • 2012-08-02
  • 2018-09-10
  • 2021-05-08
  • 2018-08-19
  • 2019-01-05
  • 2019-10-20
相关资源
最近更新 更多