From 9072e85ff0596ec691cb4c31fd77f85bf679d18d Mon Sep 17 00:00:00 2001 From: zizhilong <104978@qq.com> Date: Thu, 11 Feb 2016 15:49:29 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86Driver=E5=AF=B9?= =?UTF-8?q?=E8=A1=A8=E4=B8=AD=E6=9F=90=E5=AD=97=E6=AE=B5=E9=80=9A=E8=BF=87?= =?UTF-8?q?=E4=B8=BB=E9=94=AE=E6=89=B9=E9=87=8F=E6=9B=B4=E6=96=B0=E7=9A=84?= =?UTF-8?q?=E5=8A=9F=E8=83=BD.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 测试用代码. $m=M('think\model\Adv:log'); for($i=0;$i<=10000;$i++) { $m->bulkSave(array('id'=>$i,'admin_id'=>$i*2)); } $m->bulkSave(true); 对一万条记录的特定字段做单独更新,耗时0.46秒.如不使用字段绑定或者缩减绑定字符.可能会更小. --- library/think/db/Driver.php | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/library/think/db/Driver.php b/library/think/db/Driver.php index fc9fe036..f94ac952 100644 --- a/library/think/db/Driver.php +++ b/library/think/db/Driver.php @@ -924,6 +924,51 @@ abstract class Driver return $this->execute($sql, $this->getBindParams(true), !empty($options['fetch_sql']) ? true : false); } + /** + * 批量更新某字段 + * @access public + * @param mixed $field 字段名 + * @param mixed $pk 主键名 + * @param mixed $dataSet 数据集 + * @param mixed $operator 运算符 + * @param array $options 参数表达式 + **/ + public function updateFieldAll($field,$pk,$dataSet,$operator = '=',$options = []) + { + $values = []; + $this->bind = array_merge($this->bind, !empty($options['bind']) ? $options['bind'] : []); + $field = $this->parseKey($field); + $pk = $this->parseKey($pk); + if(in_array($operator,['+','-'])){ + $operator = '= ' . $field . $operator; + } + + $value = ''; + foreach ($dataSet as $key => $val) { + if (is_array($val) && 'exp' == $val[0]) { + $value = $val[1]; + } elseif (is_null($val)) { + $value = 'NULL'; + } elseif (is_scalar($val)) { + if (0 === strpos($val, ':') && isset($this->bind[substr($val, 1)])) { + $value = $val; + } else { + $name = count($this->bind); + $value = ':' . $_SERVER['REQUEST_TIME'] . '_' . $name; + $this->bindParam( $_SERVER['REQUEST_TIME'] . '_' . $name, $val); + } + } + //没使用过非数字主键,怎么处理比较合适? + $values[] = " WHEN " .$key." THEN " . $value; + } + + $sql = 'UPDATE ' . $this->parseTable($options['table']) . ' SET ' . $field . $operator . ' CASE ' . $pk . implode(' ', $values) . ' END ' ; + //查询条件需和WHEN THEN对一致 + $sql .= ' WHERE ' . $pk . ' in (' . implode(',',array_map([$this,'parseValue'],array_keys($dataSet))) . ')'; + $sql .= $this->parseComment(!empty($options['comment']) ? $options['comment'] : ''); + return $this->execute($sql, $this->getBindParams(true), !empty($options['fetch_sql']) ? true : false); + } + /** * 批量插入记录 * @access public