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?
-
\$\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\$slepic– slepic2020年05月06日 04:18:36 +00:00Commented May 6, 2020 at 4:18
-
\$\begingroup\$ True.. I'll leave this as it is. \$\endgroup\$lewis4u– lewis4u2020年05月06日 05:15:48 +00:00Commented May 6, 2020 at 5:15
1 Answer 1
"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.
-
\$\begingroup\$ So you would say: There is no some better way than this... leave it as it is. \$\endgroup\$lewis4u– lewis4u2020年05月05日 17:49:00 +00:00Commented May 5, 2020 at 17:49