我有三个型号开发人员型号:
迁移:
$table->increments('id');
$table->string('email')->unique();
$table->unsignedInteger('programming_language_id');
$table->unsignedInteger('language_id');
$table->timestamps();
和功能
class Developer extends Model
{
public function programming_languages() {
return $this->hasMany('App\ProgrammingLanguage');
}
public function languages() {
return $this->hasMany('App\Language');
}
}
ProgrammingLanguage 模型:
迁移:
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
和功能:
protected $table = 'programming_languages';
public function developers() {
return $this->belongsToMany('App\Developer');
}
语言模型:
迁移:
$table->increments('id');
$table->string('code', 30)->unique();
$table->timestamps();
和功能:
public function developers() {
return $this->belongsToMany('App\Developer');
}
我想制作db播种机并在它们之间建立关系。我怎样才能做到这一点? 我正在尝试:创建一个工厂 DeveloperFactory
$factory->define(App\Developer::class, function (Faker $faker) {
return [
'email' => $faker->unique()->safeEmail,
'programming_language_id' => function () {
return factory(App\ProgrammingLanguage::class)->create()->id;
},
'language_id' => function () {
return factory(App\Language::class)->create()->id;
}
];
});
种子好,但它没有任何关系。只是播种数据。答案 0 :(得分:2)
首先播种语言和编程语言表,然后在开发者播种器中查询记录。
return [
'email' => $faker->unique()->safeEmail,
'programming_language_id' => App\ProgrammingLanguage::inRandomOrder()->first()->getKey(),
'language_id' => App\Language::inRandomOrder()->first()->getKey()
];