从数据中根据主键获取条件.

@param array $data 数据.

@return array 条件.
558983
protected final function getWhere($data) {
        $con = [];
        foreach ($this->primaryKeys as $f) {
            if (array_key_exists($f, $data)) {
                if (isset($data[ $f ])) {
                    $con [ $f ] = $data [ $f ];
                } else {
                    $con [ $f . ' $' ] = null;
                }
            }
        }

        return $con;
    }
855379
public function update(array $data = [])
    {
        $options = $this->parseExpress();
        $data    = array_merge($options['data'], $data);
        $pk      = $this->getPk($options);
        $where   = [];
        if (isset($options['cache']) && is_string($options['cache']['key'])) {
            $key = $options['cache']['key'];
        }

        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 (!isset($key) && is_string($pk) && isset($options['where']['AND'][$pk])) {
            $key = $this->getCacheKey($options['where']['AND'][$pk], $options, $this->bind);
        }

        //过滤无效字段
        $this->filter($data);

        // 生成UPDATE SQL语句
        $sql = $this->builder->update($data, $options);
        // 获取参数绑定
        $bind = $this->getBind();
        if ($options['fetch_sql']) {
            // 获取实际执行的SQL语句
            return $this->connection->getRealSql($sql, $bind);
        } else {
            // 执行操作
            $result = '' == $sql ? 0 : $this->execute($sql, $bind);
            if ($result) {
                if (is_string($pk) && isset($where[$pk])) {
                    $data[$pk] = $where[$pk];
                } elseif (is_string($pk) && isset($key) && strpos($key, '|')) {
                    list($a, $val) = explode('|', $key);
                    unset($a);
                    $data[$pk]     = $val;
                }
                $options['data'] = $data;
                $this->trigger('after_update', $options);
            }
            return $result;
        }
    }
392169
protected function cleanData(array $data): array
    {
        $options = $this->getOptions();

        $disallowedDataKeys = array(
            $options->getIdColumnName(),
            $options->getLeftColumnName(),
            $options->getRightColumnName(),
            $options->getLevelColumnName(),
            $options->getParentIdColumnName(),
        );

        if (null !== $options->getScopeColumnName()) {
            $disallowedDataKeys[] = $options->getScopeColumnName();
        }

        return array_diff_key($data, array_flip($disallowedDataKeys));
    }
1269249
private function getChanges(array $data)
    {
        $changes = [
            'inserted' => Arr::dot($data),
            'updated'  => [],
            'deleted'  => [],
        ];

        foreach ($this->newQuery()->pluck($this->keyColumn) as $key) {
            if (Arr::has($changes['inserted'], $key))
                $changes['updated'][$key] = $changes['inserted'][$key];
            else
                $changes['deleted'][] = $key;

            Arr::forget($changes['inserted'], $key);
        }

        return $changes;
    }
732382
public function filter(array $data)
    {
        $filteredData = [];

        foreach ($data as $value) {
            if ($this->match($value)) {
                $filteredData[] = $value;
            }
        }

        return $filteredData;
    }
310102
public function toArray(array $data = [])
    {
        return array_filter(array_merge([
            'start' => $this->start,
            'range' => $this->range,
            'sort' => $this->sort,
            'sortDir' => $this->sortDirection,
            'search' => $this->search,
            'searchNotes' => $this->searchNotes,
            'condition' => $this->condition ? json_encode($this->condition) : null
        ], $data), function ($value) {
            return $value !== null;
        });
    }
1148972
public function delete($data = null)
    {
        $this->parseOptions();

        if (!is_null($data) && true !== $data) {
            // AR模式分析主键条件
            $this->parsePkWhere($data);
        }

        if (!empty($this->options['soft_delete'])) {
            // 软删除
            list($field, $condition) = $this->options['soft_delete'];
            unset($this->options['soft_delete']);
            $this->options['data'] = [$field => $condition];

            return $this->connection->update($this);
        }

        $this->options['data'] = $data;

        return $this->connection->delete($this);
    }
276179
protected function formatData(array $data)
    {
        $formatted = [];

        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (isset($value['value'])) {
                    $formatted[$key] = $value;

                    continue;
                }

                if (count($value) >= 2) {
                    $value = [
                        'value' => $value[0],
                        'color' => $value[1],
                    ];
                }
            } else {
                $value = [
                    'value' => strval($value),
                ];
            }

            $formatted[$key] = $value;
        }

        return $formatted;
    }
919715
public function find($data = null)
    {
        $key = '';
        if ($data instanceof MongoQuery) {
            return $data->find();
        } elseif ($data instanceof \Closure) {
            call_user_func_array($data, [ & $this]);
            $data = null;
        }
        // 分析查询表达式
        $options = $this->parseExpress();
        $pk      = $this->getPk();
        if (!is_null($data)) {
            // AR模式分析主键条件
            $this->parsePkWhere($data, $options);
        } elseif (!empty($options['cache']) && true === $options['cache']['key'] && is_string($pk) && isset($options['where']['$and'][$pk])) {
            $key = $this->getCacheKey($options['where']['$and'][$pk], $options);
        }

        $options['limit'] = 1;

        // 生成查询SQL
        $query = $this->builder->select($options);
        if (is_string($pk)) {
            if (!is_array($data)) {
                if (isset($key) && strpos($key, '|')) {
                    list($a, $val) = explode('|', $key);
                    unset($a);
                    $item[$pk]     = $val;
                } else {
                    $item[$pk] = $data;
                }
                $data = $item;
            }
        }
        $options['data'] = $data;
        // 事件回调
        if ($result = $this->trigger('before_find', $options)) {
        } else {
            // 执行查询
            $readPreference = isset($options['readPreference']) ? $options['readPreference'] : null;
            $resultSet      = $this->query($options['table'], $query, $readPreference, $options['fetch_cursor'], $options['typeMap']);

            if ($resultSet instanceof Cursor) {
                // 返回MongoDB\Driver\Cursor对象
                return $resultSet;
            }
            $result = isset($resultSet[0]) ? $resultSet[0] : null;
        }
        return $result;
    }
904813
public function model(array $data = array())
    {
        $model = trim(str_replace('\\', '_', $this->model), '_');
        return $this->$model($data)->setDatabase($this);
    }
393807
public function formatTablePrimary(array $data) {
        $key = sprintf($this->getClause(self::PRIMARY_KEY), $this->quoteList($data['columns']));

        if ($data['constraint']) {
            $key = sprintf($this->getClause(self::CONSTRAINT), $this->quote($data['constraint'])) . ' ' . $key;
        }

        return $key;
    }
1147203
public function update($data) {
        #移除表中不存在字段
        $data = $this->connection->filterTableField($data);
        foreach ($data as $k => $v) {
            $this->build()->bindExpression('set', $k);
            $this->build()->bindParams('values', $v);
        }
        if (!$this->build()->getBindExpression('where')) {
            #有主键时使用主键做条件
            $pri = $this->connection->getPrimaryKey();
            if (isset($data[$pri])) {
                $this->where($pri, '=', $data[$pri]);
            }
        }
        return $this->connection->execute($this->build()->update(), $this->build()->getUpdateParams());
    }
313110
protected function arrayDotKeysFlattern(array $data)
    {
        foreach ($data as $name => $values) {
            if ($this->isIterable($values)) {
                foreach ($values as $key => $key_value) {
                    $data["$name.$key"] = $values[$key];
                }
                unset($data[$name]);
            }
        }
        return $data;
    }
271500
public function getList(array $data = array())
    {
        $sql = 'SELECT b.*, u.name AS user_name';

        if (!empty($data['count'])) {
            $sql = 'SELECT COUNT(b.backup_id)';
        }

        $sql .= ' FROM backup b
                  LEFT JOIN user u ON(b.user_id = u.user_id)
                  WHERE b.backup_id > 0';

        $where = array();

        if (isset($data['user_id'])) {
            $sql .= ' AND b.user_id = ?';
            $where[] = $data['user_id'];
        }

        if (isset($data['id'])) {
            $sql .= ' AND b.id = ?';
            $where[] = $data['id'];
        }

        if (isset($data['version'])) {
            $sql .= ' AND b.version = ?';
            $where[] = $data['version'];
        }

        if (isset($data['name'])) {
            $sql .= ' AND b.name LIKE ?';
            $where[] = "%{$data['name']}%";
        }

        $allowed_order = array('asc', 'desc');
        $allowed_sort = array('name', 'user_id', 'version',
            'id', 'backup_id', 'type', 'created');

        if (isset($data['sort'])
            && in_array($data['sort'], $allowed_sort)
            && isset($data['order'])
            && in_array($data['order'], $allowed_order)
        ) {
            $sql .= " ORDER BY b.{$data['sort']} {$data['order']}";
        } else {
            $sql .= ' ORDER BY b.created DESC';
        }

        if (!empty($data['limit'])) {
            $sql .= ' LIMIT ' . implode(',', array_map('intval', $data['limit']));
        }

        if (!empty($data['count'])) {
            return (int) $this->db->fetchColumn($sql, $where);
        }

        $results = $this->db->fetchAll($sql, $where, array('index' => 'backup_id'));
        $this->hook->attach('module.backup.list', $results, $this);
        return $results;
    }
236956
protected function toArray( $data )
    {
        if ( is_object( $data ) )
        {
            $data = (array) $data;
        }
        if ( is_array( $data ) )
        {
           foreach( $data as $key => $val )
           {
               $data[$key] = $this->toArray( $val );
           }
        }
        return $data;
    }
833739
public function insert($data = null): IResult
    {
        if(null === $data)
        {
            $data = static::parseSaveData($this);
        }
        else if(!$data instanceof \ArrayAccess)
        {
            $data = new LazyArrayObject($data);
        }
        $query = static::query($this);

        // 插入前
        $this->trigger(ModelEvents::BEFORE_INSERT, [
            'model' => $this,
            'data'  => $data,
            'query' => $query,
        ], $this, \Imi\Model\Event\Param\BeforeInsertEventParam::class);

        $result = $query->insert($data);
        if($result->isSuccess())
        {
            foreach(ModelManager::getFields($this) as $name => $column)
            {
                if($column->isAutoIncrement)
                {
                    $this[$name] = $result->getLastInsertId();
                    break;
                }
            }
        }

        // 插入后
        $this->trigger(ModelEvents::AFTER_INSERT, [
            'model' => $this,
            'data'  => $data,
            'result'=> $result
        ], $this, \Imi\Model\Event\Param\AfterInsertEventParam::class);

        // 子模型插入
        ModelRelationManager::insertModel($this);

        return $result;
    }
1234460
public static function key(array $data) {
		$data += [
			'fields' => [],
			'locked' => [],
			'excluded' => []
		];
		return static::_compile(
			array_keys(Set::flatten($data['fields'])),
			$data['locked'],
			array_keys($data['excluded'])
		);
	}