我在Laravel中使用工厂生成一个模型的多个一对多关系时遇到了问题。工厂似乎只会为每个俱乐部生成一个ClubFixture,而不是应该为每个Club生成5个ClubFixtures。
模型
俱乐部
模型
俱乐部
<?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');
}
}
ClubFixture
namespace App;
use Illuminate\Database\Eloquent\Model;
class ClubFixture extends Model
{
//Table associated with the model
protected $table = 'club_fixtures';
}
Modal Factories
$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']),
];
});
Database seeder
factory(App\Club::class, 100)->create()->each(function ($u) {
factory(App\ClubFixture::class, 5)->create();
});
Expected Result: Each Club should have 5 ClubFixtures associated with it
Actual Result: Some Clubs have no ClubFixtures, some only have one.
I've tried this answer, but get an error with saveMany does not exist and relationship is null.
You can download the SQL resulting database here.
Can someone tell me what I am doing wrong here?
php artisan db:seed
时,它会给我返回Property [id] does not exist on this collection instance.
的错误信息,有什么解决方案吗? - Luke Brandon Farrell