Laravel 如何将包含大量记录的 csv 文件上传到数据库中
How to upload a csv file containing large records into database in Laravel
我正在尝试上传包含大约 10,000 条记录的 .csv 或 .xls 文件。对于第一次尝试,下面的 function/code 读取了 csv 文件,并能够在 ~2 分钟内将大约 1600 rows/records 插入交易 table, 没有代码行:set_time_limit(0); 我得到了:最大执行超时 错误
第二次尝试,现在使用代码:set_time_limit(0); 这一次,10,000 条记录约 11 分钟后插入.
我现在的问题是:
1.How 我可以读取一个 csv/xls 文件并将它的 records/rows 插入到 [=52 中的数据库中吗? =] 应用程序,非常快?
2.The实践,'set_time_limit(0)',我这里用过,好用吗?有没有更好的方法可以解决这个问题?
3.Before 读取和插入发生,我是否可以确定完成 operation/execution 所需的 time/maximum 时间?
public function importDataSet(Request $request)
{
if(Input::hasFile('file')){
$file = Input::file('file');
$uname = uniqid();
$oname = $file->getClientOriginalName();
$filename = $uname.$oname;
//create a folder, data-sets, if not exist in the public folder
$filelocation = 'data-sets';
$filepath=$file->move($filelocation, $filename);
ini_set('auto_detect_line_endings', TRUE);
$header = '';
$rows = array_map('str_getcsv', file($filepath));
$header = array_shift($rows);
$csv = array();
set_time_limit(0);//reset maximum execution time to infinity for this function
foreach ($rows as $row) {
$csv[] = $row;//Is not used
//eturn $rows;
$transaction = new Transaction;
$transaction->dataset_id = 1;
$transaction->itemsets=json_encode($row);
$transaction->save();
}
}else{
//noting here
}
return 'Success';
}
在我看来,这是像 Eloquent 这样的活动记录 ORM 的一大缺点。现在您正在为您保存的每条记录执行数据库查询,这本身就是 10,000 个查询。
解决它的一种简单方法是使用 mysqlimport
,因为无论如何您都有一个 .csv 文件。不过,这主要适用于一次性上传。
另一种方法是使用模型或查询生成器的 insert()
命令。已经有一个很好的答案 几乎可以直接回答您的问题。
我正在尝试上传包含大约 10,000 条记录的 .csv 或 .xls 文件。对于第一次尝试,下面的 function/code 读取了 csv 文件,并能够在 ~2 分钟内将大约 1600 rows/records 插入交易 table, 没有代码行:set_time_limit(0); 我得到了:最大执行超时 错误
第二次尝试,现在使用代码:set_time_limit(0); 这一次,10,000 条记录约 11 分钟后插入.
我现在的问题是:
1.How 我可以读取一个 csv/xls 文件并将它的 records/rows 插入到 [=52 中的数据库中吗? =] 应用程序,非常快?
2.The实践,'set_time_limit(0)',我这里用过,好用吗?有没有更好的方法可以解决这个问题?
3.Before 读取和插入发生,我是否可以确定完成 operation/execution 所需的 time/maximum 时间?
public function importDataSet(Request $request)
{
if(Input::hasFile('file')){
$file = Input::file('file');
$uname = uniqid();
$oname = $file->getClientOriginalName();
$filename = $uname.$oname;
//create a folder, data-sets, if not exist in the public folder
$filelocation = 'data-sets';
$filepath=$file->move($filelocation, $filename);
ini_set('auto_detect_line_endings', TRUE);
$header = '';
$rows = array_map('str_getcsv', file($filepath));
$header = array_shift($rows);
$csv = array();
set_time_limit(0);//reset maximum execution time to infinity for this function
foreach ($rows as $row) {
$csv[] = $row;//Is not used
//eturn $rows;
$transaction = new Transaction;
$transaction->dataset_id = 1;
$transaction->itemsets=json_encode($row);
$transaction->save();
}
}else{
//noting here
}
return 'Success';
}
在我看来,这是像 Eloquent 这样的活动记录 ORM 的一大缺点。现在您正在为您保存的每条记录执行数据库查询,这本身就是 10,000 个查询。
解决它的一种简单方法是使用 mysqlimport
,因为无论如何您都有一个 .csv 文件。不过,这主要适用于一次性上传。
另一种方法是使用模型或查询生成器的 insert()
命令。已经有一个很好的答案