Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update multiple rows from a single query using eloquent/fluent?

I was learning about How to insert multiple rows from a single query using eloquent/fluent and I found the answer here

Can somebody share any documentation about how to update bulk rows in single query?

My queries 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;
like image 515
Pankaj Avatar asked Nov 07 '22 20:11

Pankaj


1 Answers

You can solve the issue using a single MySQL query. It can be implemented in Laravel Eloquent using DB::raw() method.

**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);
like image 134
Ishrat Sharmin Avatar answered Nov 15 '22 04:11

Ishrat Sharmin