当我尝试将多个数据同时保存到数据库时,我的代码有问题,这是我保存到数据库中的代码:
I have problem with my code when i'm trying to save multiple data into database at the same time, this is my code to save into database:
foreach ($data as $value) {
$model->route = $value[0][1];
$model->begin_point = $value[0][2];
$model->begin_point = $value[0][3];
$model->save();
}
return $this->redirect('index');
每次我试图保存时,我只得到最后一个数据数组可以保存到数据库中.有人可以帮我吗?或者如果有人可以提供教程,那将是真正的帮助.
every i'm trying to save, i'm only get the last data array can save into database. could someone help me? or if someone could provide a tutorial, that would be a real help.
通过循环多个值来创建一个数组.
Create an array by looping your multiple values.
$data- has multiple values
$bulkInsertArray = array();
foreach($data as $value){
$bulkInsertArray[]=[
'columnName1'=>$value[0][1],
'columnName2'=>$value[0][2],
'columnName3'=>$value[0][3]
];
}
检查 $bulkInsertArray 是否为空
Check $bulkInsertArray in not empty
if(count($bulkInsertArray)>0){
$columnNameArray=['columnName1','columnName2','columnName3'];
// below line insert all your record and return number of rows inserted
$insertCount = Yii::$app->db->createCommand()
->batchInsert(
$tableName, $columnNameArray, $bulkInsertArray
)
->execute();
}
希望这些代码可能会有所帮助.
Hope these code may be helpful.
这篇关于在 Yii 2 中将多个数据插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!