【问题标题】:Insert multi record to database with yii2使用 yii2 将多条记录插入数据库
【发布时间】:2016-09-19 18:52:45
【问题描述】:

我想在一个操作中将许多记录插入数据库。

在这个控制器中,我使用 foreach 插入数据库,但只是 最后一条记录 插入数据库,我不知道为什么。我想将所有记录插入数据库。

我的控制器:

              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]);
                }

【问题讨论】:

    标签: yii yii2 yii2-advanced-app


    【解决方案1】:

    一种简单的方法是基于您应该在 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();
    

    【讨论】:

    • 谢谢它有效。你能用 batchinsert 告诉我这个动作吗?
    • 非常感谢。很有用
    猜你喜欢
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 2023-04-03
    • 2018-05-07
    • 1970-01-01
    • 2016-08-17
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多