查找单条记录
@access public
@param  mixed     $data  主键值或者查询条件（闭包）
@param  mixed     $with  关联预查询
@param  bool      $cache 是否缓存
@param  bool      $failException 是否抛出异常
@return static|null
@throws exception\DbException
544010
public function get($data, $with = [], $cache = false, $failException = false)
    {
        if (is_null($data)) {
            return;
        }

        if (true === $with || is_int($with)) {
            $cache = $with;
            $with  = [];
        }

        return $this->parseQuery($data, $with, $cache)
            ->failException($failException)
            ->find($data);
    }
896499
protected function parseQuery(&$data, $with, $cache)
    {
        $result = $this->with($with)->cache($cache);

        if ((is_array($data) && key($data) !== 0) || $data instanceof Where) {
            $result = $result->where($data);
            $data   = null;
        } elseif ($data instanceof \Closure) {
            $data($result);
            $data = null;
        } elseif ($data instanceof Query) {
            $result = $data->with($with)->cache($cache);
            $data   = null;
        }

        return $result;
    }
961247
public function save($data=null, $where=null)
    {
        $this->set($data, $where);
        $query = $this->getQuery();
        
        if (isset($query['table'])) {
            $table = $query['table'][0];
            $pk = $this->getPrimaryKey($table);
        } else {
            $table = $this->getTableName();
            $pk = $this->getPrimaryKey();
        }
        if (!isset($pk)) {
            throw new Exception('Can\'t get primary key of table:' . $table);
        }
        if ($data && isset($data[$pk]) && $data[$pk]) {
            $this->where([$pk => $data[$pk]]);
        }
        
        // verify data
        $mdata = $query->get('data');
        $mwhere = $query->get('where');
        
        if (!$query->formatted()) {
            $mdata = static::formatInput($mdata);
            $query->remove('data')->setRaw('data', $mdata);
            
            $res = static::verifyData($mdata);
            if ($res['errcode']) {
                return $res;
            }
        }
        
        if (static::isEmptyData($mdata)) {
            return ErrorInfo::error('没有更新的数据');
        }
        
        if (!$mwhere) {
            // clone query
            $clone = $query->clone();
            $res = static::setQuery($clone)->verifyUnique($mdata, $mwhere);
            if ($res['errcode']) {
                return $res;
            }
        }
        
        $row = null;
        if (!empty($mwhere)) {
            // clone query
            $this->setQuery($query->clone());
            $row = $this->find();
        }
        
        if ($row) {
            $this->setQuery($query)->update()->query();
            
            $id = $row[$pk];    // first row id
        } else {
            $id = $this->setQuery($query)->insert()->query(); // insert id
            
            if (!$id) {
                return ErrorInfo::error('操作未获取 insertId');
            }
        }
        
        return ErrorInfo::success(['id' => $id]);
    }
518752
public static function getException($transactionId, $responseCode, $responseText, $item)
    {
        $responseCode = (string)$responseCode;
        $code = null;
        $message = null;

        if ($responseCode == '00') {
            return null;
        }

        if (isset($item->Processor) && isset($item->Processor->Response)) {
            $error = self::nvpToArray($item->Processor->Response);
            $code = $error['Code'];
            $message = $error['Message'];
        }

        return new HpsProcessorException($transactionId, $code, $message, $responseCode, $responseText);
    }
998605
public function execute($cache = true) {
        // @todo Execute sql here
        if (strlen($this->_sql_query)) {
            // Get cache key
            $cache_key = sha1($this->_sql_query);
            
            // If cache exists and cache is enable
            $config = Config::get('db');
            $cache_enable = isset($config->cache) ? $config->cache : false;
            $cache_time = isset($config->cache_time) ? $config->cache_time : 1440;
            
            if ($cache_enable) {
                if (Cache::exists($cache_key) && $cache) {
                    return Cache::get($cache_key);
                }
            }
            
            // Return contents
            $results = [];

            // Open connection
            if (is_null($this->db) ||
                ($this->db instanceof \mysqli && !$this->db->ping())) {
                $this->__connect();
            }

            // Execute command
            $return = $this->db->query($this->_sql_query);
            
            // Close connection
            $thread = $this->db->thread_id;
            $this->db->close();
            $this->db->kill($thread);
            
            // Log executed query
            array_push(self::$_last_commands, $this->_sql_query);
        
            
            if (is_object($return) && isset($return->num_rows)) {
                while ($row = $return->fetch_array()) {
                    array_push($results, $row);
                }
                
                // Save cache (overwrites existing)
                if ($cache) {
                    Cache::save($cache_key, $results, true, $cache_time);
                }
                
                return $results;
            }
            
            return $return;
        }
    }
749520
public function update($data = null): IResult
    {
        $query = static::query($this);
        $query = $this->parseWhereId($query);
        if(null === $data)
        {
            $data = static::parseSaveData($this);
        }
        else if(!$data instanceof \ArrayAccess)
        {
            $data = new LazyArrayObject($data);
        }

        // 更新前
        $this->trigger(ModelEvents::BEFORE_UPDATE, [
            'model' => $this,
            'data'  => $data,
            'query' => $query,
        ], $this, \Imi\Model\Event\Param\BeforeUpdateEventParam::class);

        if(!isset($query->getOption()->where[0]))
        {
            throw new \RuntimeException('use Model->update(), primary key can not be null');
        }

        $result = $query->update($data);

        // 更新后
        $this->trigger(ModelEvents::AFTER_UPDATE, [
            'model' => $this,
            'data'  => $data,
            'result'=> $result,
        ], $this, \Imi\Model\Event\Param\AfterUpdateEventParam::class);

        // 子模型更新
        ModelRelationManager::updateModel($this);

        return $result;
    }
255544
public function create(array $data, $callback = null)
    {
        $model = $this->query()->make($data);

        DB::transaction(function () use ($model, $data, $callback) {
            if ($model->save()) {

                if ($callback instanceof Closure) {
                    $callback($model, $data);
                }

                return true;
            }

            throw new GeneralException($model, '创建时出现问题，请再试一次。');
        });

        return $model;
    }
968652
public static function updateOrNull($data = null)
    {
        static $request;
        if (!$request) {
            $request = Di::getDefault()->getShared('request');
        }

        if (!$request->isPost() && !$request->isPut() && !$request->isPatch()) {
            return null;
        }

        $model = new static;

        $pkName = $model->getPrimaryKey();

        $_request = $request->get();

        $instance = static::get(isset($data[$pkName]) ? $data[$pkName] : $request->getId($pkName));

        if ($data === null || !isset($data[0])) {
            foreach ($model->getSafeFields() as $field) {
                if (isset($_request[$field])) {
                    $instance->$field = $_request[$field];
                }
            }
        }

        if ($data) {
            foreach ($data as $k => $v) {
                if (is_int($k)) {
                    $field = $v;
                    if (!isset($_request[$field])) {
                        throw new MissingFieldException($field);
                    }
                    $instance->$field = $_request[$field];
                } else {
                    $instance->$k = $v;
                }
            }
        }

        return $instance->update();
    }
854922
public function all($data = null, $with = [], $cache = false)
    {
        if (true === $with || is_int($with)) {
            $cache = $with;
            $with  = [];
        }

        return $this->parseQuery($data, $with, $cache)->select($data);
    }
1266721
public function cache($cache = null)
    {
        if ($cache === null) {
            return $this->_cache;
        }

        if ($cache === false) {
            $this->_cache = false;

            return $this;
        }

        if ($cache === true) {
            $cache = 'cake_pdf';
        }

        if (!in_array($cache, Cache::configured())) {
            throw new Exception(sprintf('CakePdf cache is not configured: %s', $cache));
        }

        $this->_cache = $cache;

        return $this;
    }
191618
public function onCallbackSuccess($order, $data = null)
    {
        $paymentId  = is_array($data) ? $data['paymentId'] : $data->paymentId;

        $payerId    = is_array($data) ? $data['PayerID'] : $data->PayerID;

        $this->statusCode = 'failed';

        $this->detail = sprintf('Payment failed. Ref: %s', $paymentId);

        // Begin paypal
        try {

            $this->setContext();

            $payment = Payment::get($paymentId, $this->apiContext);
            
            $execution = new PaymentExecution();

            $execution->setPayerId($payerId);

            $payment->execute($execution, $this->apiContext);

            $payment = Payment::get($paymentId, $this->apiContext);

            $this->statusCode = 'completed';

            $this->transactionId = $payment->id;

            $this->detail = 'Success';

        } catch (PayPalConnectionException $e) {

            $response = json_decode($e->getData());

            throw new GatewayException(
                sprintf(
                    '%s: %s',
                    $response->name,
                    isset($response->message) ? $response->message : 'Paypal payment Failed.'
                ),
                1001,
                $e
            );

        } catch (\Exception $e) {

            throw new GatewayException(
                $e->getMessage(),
                1000,
                $e
            );

        }
    }
1081110
public function update($data = null, $all = false)
    {
        if (is_null($data)) $data = $this->_data;
        if (!$data && !isset($this->options['increment'])) return NULL;

        $this->updatedAt && $data['updated_at'] = $this->_getTime();

        if($data)
            $columns = '`' . implode('` = ?, `', array_keys($data)). '` = ?,';
        else
            $columns = '';

        $increment = '';
        if(isset($this->options['increment']) && $this->options['increment']) {
            foreach ($this->options['increment'] as $field => $value)
                $increment .= "`{$field}` = `$field` + {$value},";
            $increment = rtrim($increment, ',');
        }else{
            $columns = rtrim($columns, ',');
        }

        $sql = 'UPDATE ' . $this->getTableName() . ' SET ' . $columns . $increment . ' WHERE ';

        $params = array();
        // 如果有设置主键
        if (isset($data[$this->key])) {
            $where = $this->key . ' = ?';
            $params = array($data[$this->key]);
        } elseif (isset($this->options['where']['0'])) { // 或者有设置where
            $where = $this->options['where']['0'];
            if (isset($this->options['where']['1'])) $params = $this->options['where']['1'];
        } elseif ($all) { // 更新所有数据，慎用！
            $where = '1 = 1';
        } else {
            return NULL;
        }

        if ($statement = $this->execute($sql . $where, $data ? array_merge(array_values($data), $params) : $params))
            return $statement->rowCount();
        else
            return NULL;
    }
902071
public function execute( $query, array $data = [ ] )
    {
        $result = NULL;

        $statement = $this->database->prepare( $query );

        if ( FALSE === $statement )
        {
            $this->close();

            throw new DatabaseException( 'Failed to create prepared statement.' );
        }

        $result = $statement->execute( $data );

        $this->query = $statement->queryString;

        if ( FALSE !== $result )
        {
            $result = ( int ) $statement->rowCount();
        }

        return $result;
    }
1153794
public function update(DataAbstract $data)
    {
        if (!$data->isUpdated()) {
            return false;
        }

        //~ Reset binded fields
        $this->binds = array();

        foreach ($this->primaryKeys as $key) {
            $this->addWhere($key, $this->getDataValue($data, $key));
        }

        $set = $this->getQueryFieldsSet($data);
        if (empty($set)) {
            return false;
        }

        $where = $this->getQueryWhere();
        if (empty($where)) {
            throw new \LogicException(__METHOD__ . '|Where clause is empty!');
        }

        $query     = 'UPDATE ' . $this->getTable() . ' ' . $set . ' ' . $where;
        $statement = $this->db->prepare($query);
        $statement->execute($this->binds);

        //~ Reset some data
        $data->resetUpdated();

        //~ Clear
        $this->clear();
        $this->deleteCache($data);

        return true;
    }
175397
protected function fail($errcode=-1, $errmsg=null, $data=null)
    {
        return static::error($errcode, $errmsg, $data);
    }
109101
public function check($data = null, &$failed = null) {
        // reset var if it is defined
        $failed = null;

        $valid = $this->checkType($data, $failed) && $this->checkValueSet($data, $failed);

        if (!$valid) Structure::$lastFail = $failed;
        return $valid;
    }
92373
public function query($sql, $bind = [], $cache = false) {
        $items = null;
        $dbCache = null;
        if ($cache) {
            /* @var $dbCache DBCache */
            $dbCache = Ioc::get(DBCache::class);
            $items = $dbCache->queryCache($sql, $bind);
        }
        if (!$items) {
            $items = [];
            $this->execute($sql, $bind, false);
            $procedure = in_array(strtolower(substr(trim($sql), 0, 4)), ['call', 'exec']);
            if ($procedure) {
                do {
                    $result = $this->PDOStatement->fetchAll(PDO::FETCH_ASSOC);
                    if ($result) {
                        $items[] = $result;
                    }
                } while ($this->PDOStatement->nextRowset());

            } else {
                $items = $this->PDOStatement->fetchAll(PDO::FETCH_ASSOC);
            }
            $this->PDOStatement = null;
            if ($cache) {
                $dbCache->saveCache($sql, $bind, $items);
            }
        }
        return $items;
    }