🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 大数据节省内存处理 ### 将查询数据对象转成数组   在Laravel框架中,我们可以在使用连贯查询的时候使用`toArray()`方法将查询的数据对象转换成数组,方便使用。   那么在Yii2中,我们可以使用`asArray()`得到同样的效果。当然,如果查询的数据量比较大的话这样做能节省服务器内存,如: ```php $article = Article::find()->asArray()->all(); ``` ### 批量操作数据 #### 批量读取数据 例如一次性取100条,我们分十次取一次取10条。使用`betch()`进行操作,如下: ```php foreach(Article::find()->betch(10) as $article) { print_r(count($article)); } ``` #### 批量写入数据 下面是一个将excel数据导入到数据库的例子,使用`batchInsert()`方法进行数据的写入,提高效率。 ```php /** * 导入Excel操作 */ public function actionImportExcel() { $inputFile = 'uploads/branches_file.xlsx'; try { $inputFileType = PHPExcel_IOFactory::identify($inputFile); $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHPExcel = $objReader->load($inputFile); } catch (Exception $e) { dir('Error'); } $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); $highestColumn = $sheet->getHighestColumn(); for ($row = 1; $row <= $highestRow; $row++) { $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, null, true, false); if ($row == 1) { continue; } /*$branch = new Branches; $branch->branch_id = $rowData[0][0]; $branch->companies_company_id = $rowData[0][1]; $branch->branch_name = $rowData[0][2]; $branch->branch_address = $rowData[0][3]; $branch->branch_created_date = $rowData[0][4]; $branch->branch_status = $rowData[0][5]; $branch->save();*/ if(!empty($rowData[0][0])){ $data[] = [$rowData[0][0],$rowData[0][1],$rowData[0][2],$rowData[0][3],$rowData[0][4],$rowData[0][5]]; } } Yii::$app->db->createCommand() ->batchInsert('branches', ['branch_id','companies_company_id','branch_name','branch_address','branch_created_date','branch_status'], $data) ->execute(); die('okay'); } ```