【发布时间】:2018-08-11 02:59:28
【问题描述】:
我在使用 Laravel 中的工厂为模型生成多个一对多关系时遇到问题。工厂似乎每个俱乐部只生成一个 ClubFixture,而他们应该为每个俱乐部生成 5 个 ClubFixture。
模型
俱乐部
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Club extends Model
{
//Table associated with the model
protected $table = 'clubs';
protected $fillable = ['name', 'league', 'age_group', 'colour', 'county', 'country'];
public function fixtures(){
return $this->hasMany('App\ClubFixture', 'club_id', 'id');
}
}
俱乐部夹具
namespace App;
use Illuminate\Database\Eloquent\Model;
class ClubFixture extends Model
{
//Table associated with the model
protected $table = 'club_fixtures';
}
模态工厂
$factory->define(App\Club::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'league' => $faker->word,
'age_group' => $faker->word,
'colour' => $faker->hexcolor,
'county' => $faker->state,
'country' => $faker->country,
'emblem' => $faker->imageUrl(80, 80),
'banner' => $faker->imageUrl,
'matches' => $faker->randomDigit,
'wins' => $faker->randomDigit,
'losses' => $faker->randomDigit,
];
});
$factory->define(App\ClubFixture::class, function (Faker\Generator $faker) {
return [
'club_id' => function () {
return factory(App\Club::class)->create()->id;
},
'opposition' => $faker->name,
'address' => $faker->address,
'datetime' => $faker->dateTimeBetween('now', '+30 weeks'),
'type' => $faker->randomElement(['home', 'away', 'none']),
];
});
数据库播种器
factory(App\Club::class, 100)->create()->each(function ($u) {
factory(App\ClubFixture::class, 5)->create();
});
预期结果:每个俱乐部应该有 5 个与之关联的 ClubFixtures
实际结果:有些俱乐部没有球具,有些只有一个。
我已经尝试过这个answer,但得到一个错误,即 saveMany 不存在并且关系为空。
您可以下载 SQL 结果数据库here。
谁能告诉我我在这里做错了什么?
【问题讨论】:
标签: laravel eloquent one-to-many factory