How to mass insert or update in a single query (not a for loop of queries) using Laravel 4.2 How to mass insert or update in a single query (not a for loop of queries) using Laravel 4.2 laravel laravel

How to mass insert or update in a single query (not a for loop of queries) using Laravel 4.2


Typically the sort of sql you would be using would be something along the lines of the following:-

    insert into `TABLE` ( `FIELD1`,`FIELD2`, `FIELD3` ) values ( 'VALUE1','VALUE2','VALUE3' )    on duplicate key        update            `FIELD1`='VALUE1',            `FIELD2`='VALUE2',            `FIELD1`='VALUE3';

How you would use this with laravel I couldn't tell you! Oops - forgot the field names in the update part


<?php$valuesArray = [];foreach( $cards as $cardName => $quantity ) {    $valuesArray[] = "('".$user->username."','".$card->uid."','".$quantity."')";   }$db->query (    "INSERT INTO `TABLE` ( `username`,`card_uid`, `have_quantity` ) VALUES ".implode( ',', $valuesArray )."    ON DUPLICATE KEY UPDATE `have_quantity` = VALUES(`have_quantity`);" );

Make sure you have a primary key on username and card_uid. Also don't forget to escape the values and to only run the query if $valuesArray is not empty.


If you don't want duplicates have your DB schema prevent the entry of duplicate entries. Catch the error in this case and just continue on.