使用 yii2 向数据库中插入多条记录
Insert multi record to database with yii2
我想在 one 操作中将 many 记录插入数据库。
在这个控制器中,我使用 foreach 插入数据库,但只有 last record 插入数据库,我不知道为什么。我想插入所有条记录到数据库。
我的控制器:
if (isset($_POST['month'])) {
$name = $_POST['month'];
$price = $_POST['Request'];
$i = 0;
foreach ($name as $month) {
$model->month = $month;
$model->price = $price['price'];
$model->save(false);
$i++;
}
$pay_info = [
'cost' => $price['price'],
'title' => 'title'];
return $this->render('payment', ['pay_info' => $pay_info]);
}
一个简单的方法是基于这样一个事实,即您应该为每个要保存的实例在 foreach 中创建一个新模型
(你的控制器代码不完整所以我不知道你的型号)
if (isset($_POST['month'])) {
$name = $_POST['month'];
$price = $_POST['Request'];
$i = 0;
foreach ($name as $month) {
$model = new YourModel(); /* here */
$model->month = $month;
$model->price = $price['price'];
$model->save(false);
$i++;
}
$pay_info = [
'cost' => $price['price'],
'title' => 'title'];
return $this->render('payment', ['pay_info' => $pay_info]);
}
但我建议也探索 batchInsert 命令 http://www.yiiframework.com/doc-2.0/yii-db-command.html#batchInsert()-detail
对于批量插入,您可以构建一个包含月份和价格的关联数组,例如:
$my_array= [
['January', 30],
['Febrary', 20],
['March', 25],
]
\Yii::$app->db->createCommand()->
batchInsert('Your_table_name', ['month', 'price'],$my_array)->execute();
我想在 one 操作中将 many 记录插入数据库。
在这个控制器中,我使用 foreach 插入数据库,但只有 last record 插入数据库,我不知道为什么。我想插入所有条记录到数据库。
我的控制器:
if (isset($_POST['month'])) {
$name = $_POST['month'];
$price = $_POST['Request'];
$i = 0;
foreach ($name as $month) {
$model->month = $month;
$model->price = $price['price'];
$model->save(false);
$i++;
}
$pay_info = [
'cost' => $price['price'],
'title' => 'title'];
return $this->render('payment', ['pay_info' => $pay_info]);
}
一个简单的方法是基于这样一个事实,即您应该为每个要保存的实例在 foreach 中创建一个新模型 (你的控制器代码不完整所以我不知道你的型号)
if (isset($_POST['month'])) {
$name = $_POST['month'];
$price = $_POST['Request'];
$i = 0;
foreach ($name as $month) {
$model = new YourModel(); /* here */
$model->month = $month;
$model->price = $price['price'];
$model->save(false);
$i++;
}
$pay_info = [
'cost' => $price['price'],
'title' => 'title'];
return $this->render('payment', ['pay_info' => $pay_info]);
}
但我建议也探索 batchInsert 命令 http://www.yiiframework.com/doc-2.0/yii-db-command.html#batchInsert()-detail
对于批量插入,您可以构建一个包含月份和价格的关联数组,例如:
$my_array= [
['January', 30],
['Febrary', 20],
['March', 25],
]
\Yii::$app->db->createCommand()->
batchInsert('Your_table_name', ['month', 'price'],$my_array)->execute();