不必要更新所有數(shù)據(jù),因為如果更新很多其他無用的數(shù)據(jù)的話,后期如果數(shù)據(jù)很多,會有很多的資源浪費(fèi),因為你一次操作最多是2條數(shù)據(jù)狀態(tài)的切換,比如,當(dāng)前選中的是4,你想切換到25,其實是4的state變成0,25的state變成1.所以,你只需要向后臺傳一個這樣的json:
{
4:0,
25:1
}
json_decode 轉(zhuǎn)換之后的數(shù)組格式為這樣
$req = [4=>0,25=>1]
然后foreach處理
foreach($req as $key => $re) {
$db->where('id', '=', $key)->update(['state' => $re]);
}
因為最多只有兩次循環(huán),所以對性能影響并不是很大。
或者可以這樣,需要將數(shù)據(jù)用array_keys ,array_values 處理一下。
/**
* update `表名` set state = case id
* when 4 then 0
* when 25 then 1
* end where id in (4,25)
* @param $table 表名
* @param $conditions_field 條件字段,此處為 id
* @param $values_field 需要被更新的字段 ,此處為state
* @param $conditions 條件 [4,25]
* @param $values 被更新的值 [0,1]
* @return int
*/
public function batchUpdate($table,$conditions_field, $values_field, $conditions, $values)
{
$sql = 'update ' . $table . ' set '. $values_field .' = case ' .$conditions_field;
foreach ($conditions as $key => $condition) {
$sql .= ' when ' . $condition . ' then ?';
}
$sql .= ' end where id in (' . implode(',', $conditions) . ')';
return $db->update($sql, $values);
}