Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent Runs two queries on update?

Tags:

I was curious to know, if laravel eloquent runs only one query on updating a row. So I tried the following

Route::get('/cli', function(){
   DB::enableQueryLog();

   $client = Client::findOrFail(1);
   $client->first_name = 'Noob';
   $client->save();
   return response()->json([
       'client' => $client->first_name,
       'query' => DB::getQueryLog()
   ], 200);
});

This gave me the following result

{
     "client": "Noob",
     "query": [{
                 "query": "select * from `clients` where `clients`.`id` = ? limit 1",
     "bindings": [
           1
        ],
     "time": 0.71
},
{
      "query": "update `clients` set `first_name` = ?, `updated_at` = ? where `id` = ?",
      "bindings": [
           "Noob",
           "2017-10-07 12:03:05",
           1
         ],
      "time": 3.36
}
]
}

So I thought about using the DB Facade.

Route::get('/cli', function(){
   DB::enableQueryLog();
$client = DB::select("update clients set first_name= 'Admin test' WHERE id=1");

   return response()->json([
       'client' => $client->first_name,
       'query' => DB::getQueryLog()
   ], 200);
});

and the result is

{
"client": [],
"query": [
{
"query": "update clients set first_name= 'Admin test' WHERE id=1",
"bindings": [],
"time": 3.2
}
]
}

This one ran only one query though it did not returned the Client instance. My question is, for a high traffic server which method or strategy is required to use? Is there any other better techniques or tricks in eloquent to use?

like image 575
Noob Coder Avatar asked Oct 07 '17 06:10

Noob Coder


1 Answers

You can change below query to eloquent

$client = DB::select("update clients set first_name= 'Admin test' WHERE id=1");

to

$data=['first_name'=>'Admin test'];
     Client::where('id', '=', 1)->update($data);

If i understood your question correctly then in first query you are selecting and then updating value so it will definitely execute two queries. In your second method you are not fetching any think from db so it will be faster than first

like image 52
Vision Coderz Avatar answered Oct 11 '22 14:10

Vision Coderz