public function update(array $data)
{
$options = $this->parseExpress();
$pk = $this->getPk($options);
if (isset($options['cache']) && is_string($options['cache'])) {
$key = $options['cache'];
}
if (empty($options['where'])) {
// 如果存在主键数据 则自动作为更新条件
if (is_string($pk) && isset($data[$pk])) {
$where[$pk] = $data[$pk];
if (!isset($key)) {
$key = 'think:' . $options['table'] . '|' . $data[$pk];
}
unset($data[$pk]);
} elseif (is_array($pk)) {
// 增加复合主键支持
foreach ($pk as $field) {
if (isset($data[$field])) {
$where[$field] = $data[$field];
} else {
// 如果缺少复合主键数据则不执行
throw new Exception('miss complex primary data');
}
unset($data[$field]);
}
}
if (!isset($where)) {
// 如果没有任何更新条件则不执行
throw new Exception('miss update condition');
} else {
$options['where']['AND'] = $where;
}
} elseif (is_string($pk) && isset($options['where']['AND'][$pk]) && is_scalar($options['where']['AND'][$pk])) {
$key = 'think:' . $options['table'] . '|' . $options['where']['AND'][$pk];
}
// 生成UPDATE SQL语句
$sql = $this->builder()->update($data, $options);
// 获取参数绑定
$bind = $this->getBind();
if ($options['fetch_sql']) {
// 获取实际执行的SQL语句
return $this->connection->getRealSql($sql, $bind);
} else {
// 检测缓存
if (isset($key) && Cache::get($key)) {
// 删除缓存
Cache::rm($key);
}
// 执行操作
return '' == $sql ? 0 : $this->execute($sql, $bind);
}
}