Created
September 9, 2020 12:21
-
-
Save jakeydevs/4a30e6c9e738a6b164822a58f81e6a09 to your computer and use it in GitHub Desktop.
Laravel command to mass add data using a factory - focusing on speed of insert!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Console\Commands; | |
use App\Models\User; | |
use Illuminate\Console\Command; | |
class DummyData extends Command | |
{ | |
/** | |
* The name and signature of the console command. | |
* | |
* @var string | |
*/ | |
protected $signature = 'create:data | |
{rows : How many rows should we create?}'; | |
/** | |
* The console command description. | |
* | |
* @var string | |
*/ | |
protected $description = 'Creates a set of big data which can be used to stress test the system'; | |
/** | |
* Create a new command instance. | |
* | |
* @return void | |
*/ | |
public function __construct() | |
{ | |
parent::__construct(); | |
} | |
/** | |
* Execute the console command. | |
* | |
* @return int | |
*/ | |
public function handle() | |
{ | |
//-- Timer | |
$this->start = microtime(true); | |
//-- Chunk our data | |
$rows = $this->argument('rows', 100000); | |
$this->info('Adding ' . number_format($rows) . ' Rows of data'); | |
//-- Change this to either one of the insert systems to compare | |
//-- times 👍 | |
$this->createChunked($rows); | |
$took = number_format(microtime(true) - $this->start, 5); | |
$this->info('✔ Done (' . $took . 's)'); | |
return true; | |
} | |
/** | |
* Use the internal system to make the data | |
* | |
* @param int $rows | |
* @return boolean | |
*/ | |
public function createChunked($rows) | |
{ | |
$chunk = 500; | |
$chunks = ceil($rows / $chunk); | |
$this->info('Processing in ' . $chunks . ' chunks'); | |
$this->output->progressStart($chunks); | |
$insert = []; | |
//-- Loop through each chunk | |
foreach (range(1, $chunks) as $cNum) { | |
//-- Create specific amount of rows if last chunk | |
if ($cNum == $chunks) { | |
$chunk = $rows - ($chunk * ($cNum - 1)); | |
} | |
//-- Loop | |
foreach (range(0, $chunk) as $n) { | |
$p = User::factory()->make(); | |
$d = $p->toArray(); | |
$d['created_at'] = \Carbon\Carbon::parse($d['created_at'])->format("Y-m-d H:i:s"); | |
$insert[] = $d; | |
} | |
\DB::table('users')->insert($insert); | |
$this->output->progressAdvance(); | |
} | |
$this->output->progressFinish(); | |
return true; | |
} | |
/** | |
* Use the factory system to make the data | |
* | |
* @param int $rows | |
* @return boolean | |
*/ | |
public function createFactories($rows) | |
{ | |
User::factory()->count($rows)->create(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment