Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving multiple rows in a single query

Tags:

cakephp

Is there anyway to have cake do a multi-row insert in a single query without writing raw SQL to do this? The saveMany and saveAssociated options will only save multiple rows in a single transaction, but that transaction contains multiple insert statements so these methods are clearly not a solution to write heavy applications.

Thanks for reading.

like image 779
cnizzardini Avatar asked Jun 11 '13 02:06

cnizzardini


1 Answers

Yes

Though it's not a common practice to do so in app-land code, and doing so removes the possibility to use almost any application logic (validation rules, behaviors, events etc.). You can see an example of doing this in the way fixtures are loaded:

$db = ConnectionManager::getDataSource('default');

$table = "stuffs";
$fields = array('id', 'name');
$values = array(
    array(1, 'one'),
    array(2, 'two'),
    ...
);

$result = $db->insertMulti($table, $fields, $values);

You may also find this repository useful (either directly or as a basis for your code) which loads fixture files into your app database - using multi-inserts.

like image 176
AD7six Avatar answered Sep 29 '22 21:09

AD7six