如何以特殊顺序从数组生成伪数据

时间:2019-01-30 11:30:35

标签: laravel faker

我想在特殊的顺序是这样的...

要产生48行(每年12个月内没有重复)的假数据记录
dataYear  dataMonth  monthlyRevenue accumulatedRevenue
2015         Jan          123456            123456
2015         Feb          123456            123456
2015         Mar          123456            123456
2015         Apr          123456            123456
2015         May          123456            123456
...

下面是我的代码,有人知道如何通过Laravel-Fake吗?

<?php

use Faker\Generator as Faker;

$factory->define(App\Model\gamingdata::class, function (Faker $faker) {
$dataMonth = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
$year = [2015,2016,2017,2018];    
static $order1 = 0;
static $order2 = 0;

$order1 = $order1++;
$order2 = $order2++;
return [
    'dataYear' => $year[$order1],
    'dataMonth' => $dataMonth[$order2],
    'monthlyRevenue' => $faker->numberBetween(100000, 9000000),
    'accumulatedRevenue' => $faker->numberBetween(100000, 9000000),
];
});

3 个答案:

答案 0 :(得分:1)

通常由Seeder创建的虚拟数据(php artisan make:seeder DummyData)。我能这样吗?

$year = 2015
$dataMonth=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
for(i=0,i <23,i++){     
DB::table('table_name')->insert([
            'dateYear' => $year= $year+i,
            'dateMonth' => $dataMonth,
            'monthlyRevenue' =>  rand(1000,10000),
            'accumulatedRevenue' =>  rand(1000,10000),
        ]);i++}

https://laravel.com/docs/5.7/seeding

答案 1 :(得分:1)

您可以利用伪造者将数据直接添加到数据库中,如下所示:

factory(App\Model\gamingdata::class)->create([
    'dataYear' => $year,
    'dataMonth' => $month
]);

您必须如上所述反复进行几个月的迭代,但这应该为您提供一个良好的开端。您还可以将数字作为第二个属性传递给factory helper函数,以指示要插入的记录数。有关更多详细信息,请参见here。可以在文档的一半以下找到示例。

答案 2 :(得分:0)

最后,我尝试了@Lim Kean Phang的意见,直接在播种机中编辑需求,而不是在Factor php中编辑需求,

<?php

use Illuminate\Database\Seeder;
use App\Model\gamingdata;
use Illuminate\Support\Facades\DB;
class GamingDataTableSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    DB::table('gamingdatas')->delete();
    $year = 2014;
    $dataMonth=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

    for ( $i=0; $i <4; $i++ ) 
    {
      $year= $year+ 1;
        for ( $j=0; $j <12; $j++ )
        {
        DB::table('gamingdatas')->insert([
            'dataYear' => $year,
            'dataMonth' => $dataMonth[$j],
            'monthlyRevenue' =>  rand(1000,10000),
            'accumulatedRevenue' =>  rand(1000,10000),
        ]);
        };
    }
}
}