Lumen 9 uses data factory to generate simulation data to database and optimize filling speed

generate data

First introduce the trait in the data model:Illuminate\Database\Eloquent\Factories\HasFactory;

Example:

<?php

namespace App\Models\Entities\User;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Account extends Model {
    
    

    use HasFactory;

    protected $table = 'table_name';
}

Back to database/factoriesthe directory, according to the creation path of the model that needs to generate data namespace(above App\Models\Entities\User):

# 取 Models 后面部分即可,创建相同路径
database/factories/Entities/User

Create a model factory with a naming format such as 模型名+Factory, AccountFactoryfor example:

<?php

namespace Database\Factories\Entities\User;

use App\Models\Entities\User\Account;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class AccountFactory extends Factory {
    
    

    protected $model = Account::class;

    /**
     * @return array
     */
    public function definition(): array {
    
    
        return [
            'data_id' => mt_rand(1, 999),
            'data_str' => Str::random(),
            'md5' => $this->faker->md5(),
            'update_date' => $this->faker->dateTimeBetween('-1 months')
            // 其它需要 faker 填充的部分参考文档
        ];
    }
}

Finally edit database/seeders/DatabaseSeeder.phpthe file:

<?php

namespace Database\Seeders;

use App\Models\Entities\User\Account;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder {
    
    

    use WithoutModelEvents;

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run(): void {
    
    
        // 避开正式环境
        if (env('APP_ENV') !== 'production') {
    
    
            // 指定生成数量,此处亦可使用 create 方法
            Account::factory(1000)->createQuietly();
        }
    }
}

After the preparation work is completed, it is executed. The root directory of the project opens the command window:

php artisan db:seed

The data is then entered into the database

Split the Seeder class

If you want to split and run a specified Seederclass, Illuminate\Database\Seederyou only need to add a class that inherits from,

Then modify the method DatabaseSeederin the to :run

$this->call(TargetClassSeeder::class);

At this point in the command window you can use:

# 默认 --class 为 DatabaseSeeder
php artisan db:seed --class=TargetClassSeeder

# 指定数据库连接
php artisan db:seed --database=another_connection

# 在生产环境中强制生成模拟数据
php artisan db:seed --force

Optimize processing speed

It is recommended facotrythat the generated number should not exceed 10,000 level, otherwise the memory limit in the PHP configuration needs to be increased

Here, 10,000 pieces of data are divided into 10 blocks, and each block is taken out and converted into 1000 array, and finally insertinserted quickly through the method

By default, the factory will insert data in a single entry, which is too inefficient

if (env('APP_ENV') !== 'production') {
    
    
    $data = Account::factory(10000)->make();

    $chunks = $data->chunk(1000);

    $chunks->each(function ($chunks) {
    
    
        Account::insert($chunks->toArray());
    });
}

Guess you like

Origin blog.csdn.net/maxsky/article/details/123996643