我有一个像这样的数据库表
|id |col2|col3|col4|
-------------------
| 1 |elm0|....|....|
| 2 |elm1|....|....|
| 3 |elm2|....|....|
|...|....|....|....|
|N+1|elmN|....|....|
我想用数组填充col2
(不是随机的)。
示例数组:
$dataArray = array(elm0, elm1, elm2,...)
我创建了这个工厂:
<?php
use Faker\Generator as Faker;
$factory->define(App\Unit::class, function (Faker $faker) {
$dataArray = array(elm0, elm1, elm2,...,elmN);
return [
'col2' => $dataArray[$index];
'col3' => $faker->'whatever';
'col4' => $faker->'whatever';
];
});
我怎么能这样做?
答案 0 :(得分:1)
你可以这样建造:
<?php
use Faker\Generator as Faker;
$factory->define(App\Unit::class, function(Faker $faker) {
$data = array(elm0, elm1, elm2,...,elmN);
foreach($data as $kye=>$value) {
$result['id'] = $key;
$result['col2'] = $value;
$result['col3'] = $faker->'whatever';
$result['col4'] = $faker->'whatever';
}
return $result;
});
当您需要运行数组时,通常foreach()
可以解决您的问题。
希望能帮助你。
干杯。
答案 1 :(得分:0)
<?php
use Faker\Generator as Faker;
$factory->define(App\Unit::class, function(Faker $faker) {
// Grab a random unit
$unit = App\Unit::orderByRaw('RAND()')->first();
// Or create a new unit
$unit = factory(App\Unit::class)->create();
return [
'id' => $unit->id,
'col2' => $faker->'whatever',
'col3' => $faker->'whatever',
'col4' => $faker->'whatever',
];
});
请检查它是否适合您。
答案 2 :(得分:0)
遇到类似的问题,因此决定跳过工厂零件,仅使用播种机。阅读以下内容时,我得到了解决方案:lukasgeiter的Seed multiple rows at once laravel 5答案。
首先,您要使用:php artisan make:seeder UnitsTableSeeder制作播种机
然后,您的播种机中将出现以下内容:
<?php
use Faker\Generator as Faker;
use Illuminate\Database\Seeder;
class UnitsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$faker = new Faker;
$data = ['elm0', 'elm1', 'elm2',...,'elmN'];
$rows = [];
foreach ($data as $element) {
$rows[] = ['col2' => $element, 'col3' => $faker->'whatever', 'col4' => $faker->'whatever'];
}
App\Unit::insert($rows);
}
}
此后,您可以像先生一样播种Units表:)
php artisan db:seed --class = UnitsTableSeeder
答案 3 :(得分:0)
如果要从数组中获取随机元素并对其进行伪造,则可以执行以下操作:
$factory->define(Rule::class, function (Faker $faker) {
$data = [
'age' => [
'borrower_age_min' => 'min:21',
'borrower_age_max' => 'max:75'
],
'affordability' => [
'annual_income' => 'integer|min:40000',
'loan_amount' => 'integer|max:3*',
],
'finance' => [
'loan_length' => 'integer|max:12',
'loan_amount' => 'integer|max:500000',
]
];
return [
'rule' => json_encode([
$faker->randomElement(
[
$data['age']['borrower_age_min'],
$data['age']['borrower_age_max'],
$data['affordability']['annual_income'],
$data['affordability']['loan_amount'],
$data['finance']['loan_length'],
$data['finance']['loan_amount']
]
)
])
];
});