radio切换切换状态 mysql语句还能有更好的写法么

单击任意 radio

更新state 还能有更好的写法么

$res = $db->where('id', 'EQ', $id)->update(['state' => '1']);
        $db->where('id', '<>', $id)->where('uid', 'EQ', Session::get('id'))->update(['state' => '0']);
        

clipboard.png

clipboard.png

阅读 2.3k
1 个回答

不必要更新所有数据,因为如果更新很多其他无用的数据的话,后期如果数据很多,会有很多的资源浪费,因为你一次操作最多是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);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题