Skip to content

Instantly share code, notes, and snippets.

@cottonaf
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cottonaf/8e13152047c459d81997 to your computer and use it in GitHub Desktop.
Save cottonaf/8e13152047c459d81997 to your computer and use it in GitHub Desktop.
Multi-insert yii models
<?php
class ActiveRecord extends CActiveRecord
{
/**
* Requires >= Yii 1.1.14;
*
* @recordAttributes is an array of key=>value pairs which can be inserted into @tableName
* @tableName is the table into which these values will be inserted. Will attempt to determine the name itself
* if left to its own devices.
**/
public function insertMany(array $recordAttributes, $tableName=null)
{
if( empty($tableName) )
$tableName = $this->tableName();
if( empty($recordAttributes) )
return;
$schema = Yii::app()->db->schema->getTable($tableName);
// explicitly exclude the primary key so that we will not have an insert error
// (otherwise it always tries to insert the pk value and it results in an error).
if( isset($schema->columns) )
{
// get a copy of this ColumnSchema so we can add it back after
// (we remove this so that it does not attempt to insert a primary key value)
if( !is_array($schema->primaryKey) )
$pkColumnSchema = $schema->columns[$schema->primaryKey];
if( !is_array($schema->primaryKey) && isset($schema->columns[$schema->primaryKey]) )
unset($schema->columns[$schema->primaryKey]);
}
$ret = $this->insertManyInChunks($recordAttributes, $schema);
// re-apply the ColumnSchema for the primary key so that it won't fail on things such as $model->deleteByPk();
if( !is_array($schema->primaryKey) && !empty($pkColumnSchema) && empty($schema->columns[$schema->primaryKey]) )
$schema->columns[$schema->primaryKey] = $pkColumnSchema;
return $ret;
}
/**
* Workhorse function for insertMany() so that large inserts are automatically broken into
* bite-sized chunks for the database. Large sets could fail, so let's make it assume
* a large set and send off nibbles; we'll be better off for it.
*
* @param array $recordAttributes, arrays of key=>value pairs to be inserted.
* @param CDbTableSchema $tableSchema, required to insert data.
* @param int $chucnkSize, size of groupings for mass insertion.
*
* @returns int, the number of records inserted.
*/
private function insertManyInChunks(array $recordAttributes, $tableSchema, $chunkSize=300)
{
$ret = 0;
$builder = Yii::app()->db->schema->commandBuilder;
foreach( array_chunk($recordAttributes, $chunkSize) as $chunk )
{
$command = $builder->createMultipleInsertCommand($tableSchema, $chunk);
$ret += $command->execute();
}
return $ret;
}
}
?>
The MIT License (MIT)
Copyright (c) 2015 Andrew Cotton
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@cottonaf
Copy link
Author

Summary

This is meant to compliment the yii CDbCommandBuilder addition to allow many records to be inserted at once. This has a few inherent flaws which I will outline presently, but it also solves some painful issues as well.

Typical use case:

$insertMe = [];
foreach($models as $model)
{
     if( $model->validate() )
          $insertMe[] = $model->attributes;
     else
          throw new CException('Model validation failed, etc. etc.');
}

SomeClass::model()->insertMany($insertMe);

Requirements

  • this class, ActiveRecord, to be placed into somewhere meaningful (protected/components/, for example)
  • any models for which this functionality is desired should extend this class.

Drawbacks

  • code has to perform some magic with table schema in order to insert properly; don't know what happens if it fails and does not set back to original state.
  • could be further developed to loop over models and extract attributes as part of the insertMany() method; this could very easily be done but I always preferred to ensure greater flexibility rather than assume that all cases would be the same.
  • has not been tested against tables with multiple keys, or composite keys. It could prove problematic without some changes.

Problems solved

  • this makes it rather trivial to add many records at once while still using models for validation (you don't have to circumvent validation so that means you don't have to re-invent the wheel.
  • this is available to all classes which extend ActiveRecord, which is the parent class for all models if you follow the same methodology as we do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment