【问题标题】:Bulk insert or update yii2批量插入或更新 yii2
【发布时间】:2015-04-08 11:14:24
【问题描述】:

我做了什么

我在表中插入批量数据如下:

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

参考号:Insert multiple data into database in Yii 2

在这里插入工作正常。

我想要什么:

现在我的问题是我们可以做类似 如果这里 columnName1 是私钥并且如果我们为该列传递空值然后执行插入操作否则执行更新操作

在 CAKEPHP 中使用相同的概念。

我正在使用 YII2。

【问题讨论】:

    标签: cakephp yii yii2 bulkinsert bulkupdate


    【解决方案1】:

    Yii2 不提供“upsert”逻辑。
    您需要将其拆分为两个操作:
    1) 插入不重复(下面的查询)
    2) 更新

    --don't insert user if login already exists
    insert into users(login, name)
    select *
    from 
    (
        select
        'l_john' as login,
        'John' as name
        union 
        select
        'l_mike' as login,
        'Mike' as name
    ) q
    left join users u
    on u.login = q.login
    where u.id is null
    

    create temp table tmp_users(login, name);
    
    insert into tmp_users(login, name) values
    ('l_john', 'John'),
    ('l_mike', 'Mike');
    
    insert into users(login, name)
    select tu.login, tu.name
    from tmp_users ti
    left join users u
    on u.login = tu.login
    

    第二个查询集更快

    【讨论】:

      【解决方案2】:

      我尝试了很多,但最后用循环完成了它:

                  foreach ($table_info_arr as $table_info)
                  {
                      $table_info_sql = array();
      
                      $model = tableInfo::find()->where(["columnName1_id" => $table_info['columnName1_id']])->one();
                      if (empty($model))
                      {
                          $model = new tableInfo();
                      }
                      $matches_info_sql['tableInfo'] = $table_info;
      
                      $model->load($table_info_sql);
                      $model->save(false);
                  }
      

      如果有更好的解决方案,请告诉我

      【讨论】:

        猜你喜欢
        • 2020-10-24
        • 2016-05-02
        • 2011-09-11
        • 2012-03-19
        • 2011-11-13
        • 2015-10-20
        • 2018-05-22
        • 1970-01-01
        • 2012-02-16
        相关资源
        最近更新 更多