单击任意 radio
更新state 还能有更好的写法么
$res = $db->where('id', 'EQ', $id)->update(['state' => '1']);
$db->where('id', '<>', $id)->where('uid', 'EQ', Session::get('id'))->update(['state' => '0']);
1 回答
![?](http://img1.sycdn.imooc.com/545869470001a00302200220-100-100.jpg)
MM们
TA贡献1886条经验 获得超2个赞
不必要更新所有数据,因为如果更新很多其他无用的数据的话,后期如果数据很多,会有很多的资源浪费,因为你一次操作最多是2条数据状态的切换,比如,当前选中的是4,你想切换到25,其实是4的state变成0,25的state变成1.所以,你只需要向后台传一个这样的json:
{
4:0,
25:1
}
json_decode 转换之后的数组格式为这样
$req = [4=>0,25=>1]
然后foreach处理
foreach($req as $key => $re) {
$db->where('id', '=', $key)->update(['state' => $re]);
}
因为最多只有两次循环,所以对性能影响并不是很大。
或者可以这样,需要将数据用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);
}
- 1 回答
- 0 关注
- 449 浏览
添加回答
举报
0/150
提交
取消