如何使用Faker在Laravel中播种多个关系 [英] How to seed multiple relationships in Laravel with Faker
问题描述
我有一个包含品牌和商店两列的数据库.每个品牌都可以欠几家商店,我想使用Laravel通过Fakers为我的数据库添加种子.
I have a database with two columns, brands and shops. Each brand can owe several shops, and I want to seed my database via Fakers using Laravel.
因此,在建立模型中的迁移和关系之后
So after setting up the migrations and the relationships in the models
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Brand extends Model
{
/**
* Get the shops for the brand.
*/
public function shops()
{
return $this->hasMany('App\Shop','sh_brand_id');
}
}
并且:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function user() {
return $this->belongsTo('App\Brand','sh_brand_id');
}
}
我想使用Factory来播种数据库.
I want to use a Factory to seed the database.
<?php
use Faker\Generator as Faker;
$factory->define(App\Shop::class, function (Faker $faker) {
return [
'name' => $faker->company,
'address' => $faker->address,
];
});
还有
use Faker\Generator as Faker;
$factory->define(App\Brand::class, function (Faker $faker) {
return [
'name' => $faker->company,
'logo_url' => $faker->imageUrl(640, 480),
'website' => $faker->url,
'description' => $faker->text(500),
'telephone_number' =>'31'. $faker->randomNumber(8),
'principal_address' => $faker->address,
'email' => $faker->unique()->safeEmail,
];
});
最后,我需要使用那些工厂来播种数据库.网站上有文档,并且有很多示例,但是我发现的每个解决方案都只允许我为每个品牌建立一个商店,并且我想为每个品牌建立许多商店.
And finally I need to seed the database using those Factories. There are documentation in the website and many examples for do it, but each solution I've found let me generate only one shop for each brand, and I want to generate many shops for each brands.
做到这一点的最佳方法是什么?
What is the best way to do this?
推荐答案
将其直接放在工厂中.我使用辅助方法getInstanceOf
来选择另一个模型的随机实例.
Put it directly in your factory. I use a helper method getInstanceOf
to pick a random instance of another model.
use Faker\Generator as Faker;
use App\Brand;
use App\Shop;
function getInstanceOf($class, $returnIdOnly = true) {
$instance = $class::inRandomOrder()->first() ?? factory($class)->create();
return $returnIdOnly ? $instance->id : $instance;
}
$factory->define(Shop::class, function (Faker $faker) {
return [
'name' => $faker->company,
'address' => $faker->address,
'sh_brand_id' => getInstanceOf(Brand::class)
];
});
然后在播种时
factory(App\Brand::class, 10);
factory(App\Shop::class, 50);
这篇关于如何使用Faker在Laravel中播种多个关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!