1
\$\begingroup\$

I recieve this array in my controller:

"sort" => array:6 [
 0 => array:2 [
 "id" => "153"
 "sort" => "2"
 ]
 1 => array:2 [
 "id" => "152"
 "sort" => "1"
 ]
 2 => array:2 [
 "id" => "154"
 "sort" => "3"
 ]
 3 => array:2 [
 "id" => "166"
 "sort" => "4"
 ]
 4 => array:2 [
 "id" => "155"
 "sort" => "5"
 ]
 5 => array:2 [
 "id" => "156"
 "sort" => "6"
 ]
]

I have made this and it works:

foreach ($request['sort'] as $model) {
 Model::where('id', $model['id'])->update(['sort' => $model['sort']]);
}

There is probably a better way to do this.... This will make so many requests on DB how many items there are inside that array.... Anyone has better ideas? Maybe there is a way to make that update all at once so there is only one request on DB?

asked May 5, 2020 at 15:40
\$\endgroup\$
2
  • \$\begingroup\$ You can write custom SQL query to handle them all at once, but such query would be really ugly. Updating multiple rows with one query Is only simple if all rows take the same update values (or rules to compute them based on previous values, ie increment operation). If Its not slowing requests Down significantly, I wouldnt bother at this point. \$\endgroup\$ Commented May 6, 2020 at 4:18
  • \$\begingroup\$ True.. I'll leave this as it is. \$\endgroup\$ Commented May 6, 2020 at 5:15

1 Answer 1

4
\$\begingroup\$

"Premature optimization is the root of all evil."

As long as this code works and causes no problem, nothing should be really done. Trying to "improve" it, most likely you will cause a severe harm to readability, maintainability and - ironically - performance.

The only thing could be suggested out of the blue is to wrap the loop in a transaction. It will be a sensible move by itself, and and also could improve the speed in case of some certain settings of the database engine.

answered May 5, 2020 at 16:28
\$\endgroup\$
1
  • \$\begingroup\$ So you would say: There is no some better way than this... leave it as it is. \$\endgroup\$ Commented May 5, 2020 at 17:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.