How to update multiple lines from one query using eloquence / fluent?

I learned how to insert multiple rows from a single query using eloquent / fluent and I found the answer here

Can anyone share any documentation on how to update massive strings in a single request?

My inquiries are below.

Update tblrole set role = 'Super Admin' where RoleID = 1;
Update tblrole set role = 'Super Admin A' where RoleID = 2;
Update tblrole set role = 'Super Admin B' where RoleID = 3;
Update tblrole set role = 'Super Admin C' where RoleID = 4;
+4
source share
3 answers

You cannot do something like this in a simple way. You can easily update multiple rows with the same value, but if you want to update a column rolewith different values, it will be difficult.

, , , , fooobar.com/questions/110712/...

0

, MySQL. Laravel Eloquent DB:: raw().

**UPDATE** tblrole **SET** role =
    **CASE** 
      WHEN RoleID = 1 THEN 'Super Admin'
      WHEN RoleID = 2 THEN 'Super Admin A'
      WHEN RoleID = 3 THEN 'Super Admin B'
      WHEN RoleID = 4 THEN 'Super Admin C'
    **END**
 **WHERE** RoleID in (1,2,3,4);
0

:

/**
* Mass (bulk) insert or update on duplicate for Laravel 4/5
* 
* insertOrUpdate([
*   ['id'=>1,'value'=>10],
*   ['id'=>2,'value'=>60]
* ]);
* 
*
* @param array $rows
*/

function insertOrUpdate(array $rows){
    $table = \DB::getTablePrefix().with(new self)->getTable();


    $first = reset($rows);

    $columns = implode( ',',
        array_map( function( $value ) { return "$value"; } , array_keys($first) )
    );

    $values = implode( ',', array_map( function( $row ) {
            return '('.implode( ',',
                array_map( function( $value ) { return '"'.str_replace('"', '""', $value).'"'; } , $row )
            ).')';
        } , $rows )
    );

    $updates = implode( ',',
        array_map( function( $value ) { return "$value = VALUES($value)"; } , array_keys($first) )
    );

    $sql = "INSERT INTO {$table}({$columns}) VALUES {$values} ON DUPLICATE KEY UPDATE {$updates}";

    return \DB::statement( $sql );

}

: https://gist.github.com/RuGa/5354e44883c7651fd15c

I don’t think I need to give any explanation, because each piece of code in the function speaks about itself.

0
source

Source: https://habr.com/ru/post/1680056/


All Articles