laravel框架存储50万条数据
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; /** * 插入50W数据脚本 * Class CreateDataCommand * @package App\Console\Commands */ class CreateDataCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:create_data'; /** * The console command description. * * @var string */ protected $description = 'Command description'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } const TABLE_NAME = 'person_'; const COLUMN_NAME_ARR = ['account','name','area','title','motto']; const RANDOM_STRING='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; /** * Execute the console command. * * @return mixed */ public function handle() { $startTime = time(); for($i = 0; $i< 500000; $i++){ $this->insertData($i); if($i % 1000 == 1){ echo "."; } } $endTime = time(); echo "success \n"; echo "time:".($endTime - $startTime); } /** * 插入数据 * 定义属性 static * @param $i */ private function insertData($i){ foreach(self::COLUMN_NAME_ARR as $columnName){ $params[$columnName] = $this->getRandomString(10); } $isSuccess = DB::table($this->getTableName($i))->insert($params); if(!$isSuccess){ echo "insert fail!\n"; } } /** * 获取表名 * @param $i * @return string */ private function getTableName($i){ return self::TABLE_NAME.($i%10); } /** * 获取随机字符 * @param $length * @return string */ private function getRandomString($length){ $result = ""; for($i=0; $i<$length-1; $i++){ $result .= self::RANDOM_STRING[mt_rand(0,strlen(self::RANDOM_STRING)-1)]; } return $result; } }
然后进入根目录执行命令
command:create_data
然后,数据就进入数据库了。
你所浪费的今天是那些死去的人所奢望的明天,你所厌恶的现在是未来的你所回不去的曾经。