php - Laravel Eloquent for loop query to single prepared query -
need converting following laravel eloquent loop query single mysql query hits database single time. hit database n number of times based on how many items in $cardquerylist.
for($i=0; $i<count($cardquerylist); $i++) { $usercard = collection::firstornew( ['username' => $cardquerylist[$i]['username'], 'card_uid' => $cardquerylist[$i]['card_uid']] ); $usercard->have_quantity = $cardquerylist[$i]['have_quantity']; $usercard->save(); } this have:
db::raw('replace users_collection (username, card_uid, have_quantity) values('.$cardquerylist[$i]["username"].', '.$cardquerylist[$i]["card_uid"].', '.$cardquerylist[$i]["have_quantity"].')'); the problem i'm using 'username' , 'card_uid' unique key find corresponding row update. issue requires me specify values fields otherwise fields lost or replaced default values.
how can have raw mysql query hit database once instead of n times in laravel eloquent code? or there way hit database once eloquent (this best don't think there's way)?
edit based on comments, can mass update db using following:
db::table((new collection)->gettable())->update([ [ 'field' => 'value', 'field2' => 'value 2', ], [ 'field' => 'value', 'field2' => 'value 3', ], ]) ->where('some_id', $id); is raw sql you're looking for, or along these lines:
foreach ($cardquerylist $cardquery) { $usercard = collection::where('username', $cardquery['username']) ->where('card_uid', $cardquery['card_uid']) ->firstornew(); $usercard->have_quantity = $cardquery['have_quantity']; $usercard->save(); }
Comments
Post a Comment