0

我做了什么

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

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

REF:在 Yii 2 中将多个数据插入数据库

在这里插入工作正常。

我想要的是:

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

在 CAKEPHP 中工作的相同概念。

我正在使用 YII2。

4

2 回答 2

0

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

第二个查询集更快

于 2015-04-08T13:42:13.170 回答
0

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

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

让我知道是否有更好的解决方案

于 2015-04-14T10:36:54.583 回答