Last active
September 12, 2018 15:10
-
-
Save molotovbliss/05b79b84925cb32b4564 to your computer and use it in GitHub Desktop.
Magento: One model save to rule them all for performance!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Insert or read all data in one big batch, smallest possible number of queries. | |
// Sauce: http://inchoo.net/dev-talk/thou-shalt-not-do-inserts-in-a-foreach-unless-you-know-the-trick/ | |
/*** Speed tests say (time in seconds): | |
100 iterations 1000 iterations 10000 iterations | |
Insert multiple 0.017 0.079 0.379 | |
Foreach in a transaction 0.074 0.501 4.701 | |
Stupid foreach 1.097 11.729 117.410 | |
**/ | |
// Resource Model: | |
$this->_getWriteAdapter()->insertMultiple($this->getMainTable(), $data); | |
// Example foreach, but one save: | |
$model = Mage::getModel('your_model/dbtable'); | |
$resource = $model->getResource(); | |
$data = [/* Array with lots of data */]; | |
$resource->beginTransaction(); | |
foreach ($data as $row) { | |
$model->setData($row)->save(); | |
} | |
$resource->commit(); | |
// Other examples | |
$write = Mage::getSingleton("core/resource")->getConnection("core_write"); | |
$table = Mage::getSingleton('core/resource')->getTableName('table_name'); | |
$rows = array( | |
array('cal_1'=>'value','cal_2'=>'value','cal_3'=>'value'), | |
array('cal_1'=>'value','cal_2'=>'value','cal_3'=>'value') | |
); | |
public function insertRows($table,$rows) | |
{ | |
$write = Mage::getSingleton('core/resource')->getConnection('core_write'); | |
$write->insertMultiple($table,$rows); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment