ThinkPHP批量更新

    /**
     * 批量更新
     *
     * @param      string   $table_name  The table name
     * @param      array    $data        The data
     * @param      string   $field       The field
     *
     * @return     boolean  ( description_of_the_return_value )
     */
    public function batch_update($table_name = '', $data = array(), $field = '')
    {
        $db_pre = C('DB_PREFIX');
        if (!$table_name || !$data || !$field) {
            return false;
        } else {
            $sql = 'UPDATE '. $db_pre . $table_name;
        }
        $con = array();
        $con_sql = array();
        $fields = array();
        foreach ($data as $key => $value) {
            $x = 0;
            foreach ($value as $k => $v) {
                if ($k != $field && !$con[$x] && $x == 0) {
                    $con[$x] = " set {$k} = (CASE {$field} ";
                } elseif ($k != $field && !$con[$x] && $x > 0) {
                    $con[$x] = " {$k} = (CASE {$field} ";
                }
                if ($k != $field) {
                    $temp = $value[$field];
                    $con_sql[$x] .= " WHEN '{$temp}' THEN '{$v}' ";
                    $x++;
                }
            }
            $temp = $value[$field];
            if (!in_array($temp, $fields)) {
                $fields[] = $temp;
            }
        }
        $num = count($con) - 1;
        foreach ($con as $key => $value) {
            foreach ($con_sql as $k => $v) {
                if ($k == $key && $key < $num) {
                    $sql .= $value . $v . ' end),';
                } elseif ($k == $key && $key == $num) {
                    $sql .= $value . $v . ' end)';
                }
            }
        }
        $str = implode(',', $fields);
        $sql .= " where {$field} in({$str})";
        // echo $sql;
        $res = M($table_name)->execute($sql);
    
        return $res;
    }
}
 function test(){
        $update_array=array();
        for ($i=2; $i <7 ; $i++) { 
            $data=array();
            $data['id']=$i;
            $data['memeber_type']=2;
            $data['memeber_type_state']=1;
            $update_array[]=$data;
        }
        $res=$this->batch_update('yl_member',$update_array,'id');
    }
UPDATE preyl_member set memeber_type = (CASE id  WHEN '2' THEN '2'  WHEN '3' THEN '2'  WHEN '4' THEN '2'  WHEN '5' THEN '2'  WHEN '6' THEN '2'  end), memeber_type_state = (CASE id  WHEN '2' THEN '1'  WHEN '3' THEN '1'  WHEN '4' THEN '1'  WHEN '5' THEN '1'  WHEN '6' THEN '1'  end) where id in(2,3,4,5,6)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。