根据条件查找多条数据
@param array $query 查询条件
@param array $sort 排序条件 array('age' => -1, 'username' => 1)
@param int $limit 页面
@param int $limit 查询到的数据条数
@param array $fields返回的字段
165180
public function find($query, $sort = array(), $skip = 0, $limit = 0, $fields = array())
    {
        $cursor = $this->collection->find($query, $fields);
        $count = $cursor->count();
        if (empty($count)) {
            return array();
        }
        if ($sort) $cursor->sort($sort);
        if ($skip) $cursor->skip($skip);
        if ($limit) $cursor->limit($limit);
        return iterator_to_array($cursor);
    }
714308
public function scopeMostVisited(Builder $query, $limit = null)
    {
        $query->select(\DB::raw('nodes.*, count(*) as `aggregate`'))
            ->join('node_site_view', 'nodes.id', '=', 'node_site_view.node_id')
            ->groupBy('nodes.id')
            ->orderBy('aggregate', 'desc');

        if ($limit)
        {
            $query->limit($limit);
        }

        return $query;
    }
1209611
public function getPaginated($limit = 1, $fields = null, $sqlQuery = false)
    {
        $sql = $this->buildQuery('select', $fields, ['count'=>null, 'field'=>'num']);
        $result = $this->executeQuery($sql);
        $row = $result->fetch_array(MYSQLI_ASSOC);
        $total = $row['num'];
        if($total == 0 && $sqlQuery == false) {
            return [];
        }
        $this->pagination->initialize($limit, $total);
        return $this->limit($limit, $this->pagination->getStartPoint())->getAll($fields, $sqlQuery);
    }
67671
public function value(Query $query, $field, $default = null)
    {
        $options = $query->getOptions();
        $result  = null;
        if ($this->cache && !empty($options['cache'])) {
            // 判断查询缓存
            $cache  = $options['cache'];
            $key    = is_string($cache['key']) ? $cache['key'] : md5($field . serialize($options));
            $result = $this->cache->get($key);
        }

        if (!$result) {
            if (isset($options['field'])) {
                $query->removeOption('field');
            }

            $query->setOption('field', $field);
            $query->setOption('limit', 1);

            $mongoQuery = $this->builder->select($query);

            // 执行查询操作
            $readPreference = isset($options['readPreference']) ? $options['readPreference'] : null;
            $cursor         = $this->query($options['table'], $mongoQuery, $readPreference, true, ['root' => 'array']);
            $resultSet      = $cursor->toArray();
            if (!empty($resultSet)) {
                $data = (array) array_shift($resultSet);
                if ($this->getConfig('pk_convert_id')) {
                    // 转换ObjectID 字段
                    $data['id'] = $data['_id']->__toString();
                }
                $result = $data[$field];
            } else {
                $result = null;
            }

            if (isset($cache)) {
                // 缓存数据
                $this->cacheData($key, $result, $cache);
            }
        }

        return !is_null($result) ? $result : $default;
    }
533092
protected function parseLimit(Query $query, $limit)
    {
        if (empty($limit)) {
            return '';
        }

        $limit = explode(',', $limit);

        if (count($limit) > 1) {
            $limitStr = '(T1.ROW_NUMBER BETWEEN ' . $limit[0] . ' + 1 AND ' . $limit[0] . ' + ' . $limit[1] . ')';
        } else {
            $limitStr = '(T1.ROW_NUMBER BETWEEN 1 AND ' . $limit[0] . ")";
        }

        return 'WHERE ' . $limitStr;
    }
841851
public function get_values_count($table, $field, array $where = [], $limit, $start, $php = false)
  {
		if ( ( $table = $this->table_full_name($table, 1) )  && ( $m = $this->db->modelize($table) ) && \count($m['fields']) > 0 )
		{
			$r = '';
			if ( $php ){
				$r .= '$db->query("';
			}
      if ( !isset($m['fields'][$field]) ){
        die("The column $field doesn't exist in $table");
      }
			$r .= "SELECT COUNT(*) AS num, `$field` AS val FROM $table";
			if ( \count($where) > 0 ){
        $r .= PHP_EOL . $this->db->get_where($where, $table);
      }
      $r .= PHP_EOL . "GROUP BY `$field`";
      $r .= PHP_EOL . "ORDER BY `$field`";
      if ( $limit ){
  			$r .= PHP_EOL . $this->get_limit([$limit, $start]);
      }
			if ( $php ){
				$r .= '");';
			}
			return $r;
		}
		return false;
  }
802423
public function findBy(array $criteria, array $sorting = null, $limit = null, $offset = null)
    {
        $queryBuilder = $this->getCollectionQueryBuilder();

        $this->applyCriteria($queryBuilder, $criteria);
        $this->applySorting($queryBuilder, (array) $sorting);

        if (null !== $limit) {
            $queryBuilder->setMaxResults($limit);
        }

        if (null !== $offset) {
            $queryBuilder->setFirstResult($offset);
        }

        $query = $queryBuilder->getQuery();

        if (null !== $limit) {
            return $this->collectionResult($query);
        }

        return $query->getResult();
    }
51344
static public function listSort($list, $field, $sort = 'asc')
    {
        if (is_array($list)) {
            $refer = array();
            $resultSet = array();
            foreach ($list as $i => $data)
                $refer[$i] = &$data[$field];
            switch ($sort) {
                case 'asc':
                    asort($refer);
                    break;
                case 'desc':
                    arsort($refer);
                    break;
            }
            foreach ($refer as $key => $val)
                $resultSet[] = &$list[$key];
            return $resultSet;
        }
        return false;
    }
894883
public function paginate(Query $query, array $countFields = [], $total = false)
    {
        $limit = $this->defaultLimit;
        if (in_array((integer)$this->request->getQuery('l', 0), $this->limits)) {
            $limit = (integer)$this->request->getQuery('l');
            $this->activeLimit = $limit;
        }
        if (!$this->activeLimit) {
            $lastLimit = $this->request->getSession()->read(join('.', [
                'LIMIT_' . $this->request->getParam('plugin'),
                $this->controller->getName(),
                $this->action
            ]));
            if ($lastLimit) {
                $limit = $lastLimit;
            }
            $this->activeLimit = $limit;
        }
        $this->request = $this->request->withData('l', $limit);

        if ($total === false) {
            $countQuery = clone $query;
            if (!empty($countFields)) {
                $countQuery->select($countFields);
            }
            $total = $countQuery->count();
        }

        if ($limit !== null && $total !== null) {
            $pages = ceil($total / $limit);
            if ($this->page > $pages) {
                $this->page = $pages;
            }
            if ($this->page < 1) {
                $this->page = 1;
            }
            $offset = ($this->page > 1) ? ($this->page - 1) * $limit : 0;
            $from = ($offset > 0) ? $offset + 1 : 1;
            $to = (($from + $limit - 1) > $total) ? $total : $from + $limit - 1;

            $query->limit($limit)->offset($offset);

            $this->paginationParams = [
                'from' => ($total === 0) ? 0 : $from,
                'page' => $this->page,
                'pages' => ($total === 0) ? 1 : $pages,
                'to' => $to,
                'total' => $total,
                'defaultLimit' => $this->defaultLimit,
                'limits' => array_combine($this->limits, $this->limits),
                'passParams' => []
            ];

            if (!empty($this->_passParams)) {
                $this->paginationParams['passParams'] = $this->_passParams;
            }
        }

        return $query;
    }
1185792
public function count(
        $query = [],
        $limit = null,
        $skip = null,
        $timeout = 2000
    ) {
        $this->getContext()->getLog()->profileStart($this->profileName . __FUNCTION__);
        $options = [
            'socketTimeoutMS' => $timeout
        ];
        if (!is_null($limit)) {
            $options['limit'] = $limit;
        }
        if (!is_null($skip)) {
            $options['skip'] = $skip;
        }
        $out = $this->mongoCollection->count($query, $options);
        if ($out === null) {
            return 0;
        }
        $this->getContext()->getLog()->profileEnd($this->profileName . __FUNCTION__);

        return $out;
    }
836099
public function findBy(array $criteria, ?array $sorting = null, $limit = null, $offset = null)
    {
        $queryBuilder = $this->getCollectionQueryBuilder();

        $this->applyCriteria($queryBuilder, $criteria);
        $this->applySorting($queryBuilder, $sorting);

        if (null !== $limit) {
            $queryBuilder->limit($limit);
        }

        if (null !== $offset) {
            $queryBuilder->skip($offset);
        }

        return $queryBuilder
            ->getQuery()
            ->getIterator()
        ;
    }
619917
private function getSearchQueryLimit($query, $limit, $offset)
	{
		if ($limit > -1) {
			$query->limit($limit);
			$query->offset($offset);
		}

		return $query;
	}
1172785
public static function query($query)
    {
        //
        static::applySchema();

        //
        $table = self::getTable();
        $whereArray = [];

        //
        if (isset($query['where'])) {
            $whereArray[] = '('.$query['where'].')';
            unset($query['where']);
        }

        //
        foreach ($query as $field => $value) {
            if (in_array($field, ['order', 'limit'])) {
                continue;
            }
            $whereArray[] = "{$field} = '{$value}'";
        }

        //
        $where = count($whereArray) > 0 ? 'WHERE '.implode(' AND ', $whereArray) : '';
        $order = isset($query['order']) ? 'ORDER BY '.$query['order'] : '';
        $limit = isset($query['limit']) ? 'LIMIT '.$query['limit'] : '';
        $sql = "SELECT * FROM {$table} {$where} {$order} {$limit}";
        $results = static::getDatabase()->getResults($sql);

        //
        foreach ($results as &$record) {
            $record = static::create($record);
        }

        return $results;
    }
1293626
private function buildQuery(string $query, int $limit): string
    {
        if (null !== $this->sourceCountry) {
            $query = sprintf('%s&sourceCountry=%s', $query, $this->sourceCountry);
        }

        return sprintf('%s&maxLocations=%d&f=%s&outFields=*', $query, $limit, 'json');
    }
587318
public function getAll($query, $limit, $offset)
    {
        // TODO: user query
        $users = $this->userManager->findBy(array(), array('lastname' => 'ASC'), $limit, $offset);

        $data = array();
        foreach ($users as $user) {
            $data[] = array(
                'securityType' => get_class($user),
                'securityId' => $user->getId(),
                'securityName' => $user->getDisplayName(),
            );
        }

        return array(
            'total' => $this->userManager->countAll(),
            'data' => $data,
        );
    }
834374
public function actionList($sort = '', $page = 1, $limit = 20)
    {
        $user_id = \Yii::$app->request->get('user_id');
        $username = \Yii::$app->request->get('username');
        $nickname = \Yii::$app->request->get('nickname');
        $group_ids = array_filter((array)\Yii::$app->request->get('group_ids'));
        $is_group_access = \Yii::$app->request->get('is_group_access');
        $is_user_access = \Yii::$app->request->get('is_user_access');
        $is_system = \Yii::$app->request->get('is_system');
        $note = \Yii::$app->request->get('note');
        $status = \Yii::$app->request->get('status');
        $limit = intval($limit);
        $order = ExtHelpers::getOrder($sort, [
            'user_id',
            'username',
            'nickname',
            'is_system',
            'note',
            'status'
        ], [], 'user_id DESC');

        $condition = '1';
        $params = [];
        if ($user_id) {
            $condition .= ' and user_id=:user_id';
            $params[':user_id'] = $user_id;
        }
        if ($username) {
            $condition .= ' and username=:username';
            $params[':username'] = $username;
        }
        if (is_numeric($is_group_access)) {
            $condition .= ' and is_group_access=:is_group_access';
            $params[':is_group_access'] = $is_group_access;
        }
        if (is_numeric($is_user_access)) {
            $condition .= ' and is_user_access=:is_user_access';
            $params[':is_user_access'] = $is_user_access;
        }
        if (is_numeric($is_system)) {
            $condition .= ' and is_system=:is_system';
            $params[':is_system'] = $is_system;
        }
        if ($note) {
            $condition .= ' and note like :note';
            $params[':note'] = '%' . $note . '%';
        }
        if ($nickname) {
            $condition .= ' and nickname like :nickname';
            $params[':nickname'] = '%' . $nickname . '%';
        }
        if ($group_ids && is_array($group_ids)) {
            $group_ids = array_filter($group_ids, function ($value) {
                return is_numeric($value);
            });
            $condition .= ' and group_ids in (' . join(',', $group_ids) . ')';
        }
        if (is_numeric($status)) {
            $condition .= ' and status=:status';
            $params[':status'] = $status;
        }
        $condition .= ' and user_id!=1';
        $data = DpAdminUser::getListByCondition($condition, $params, $order, $page, $limit);
        $list = [];
        if ($data['list']) {
            foreach ($data['list'] as $item) {
                $groupIds = StringHelper::explode($item['group_ids'], ',', true, true);
                asort($groupIds);
                $groupNames = [];
                foreach ($groupIds as $groupId) {
                    $group = DpAdminGroup::getByGroupId($groupId);
                    if ($group) {
                        $groupNames[] = $group['name'];
                    }
                }
                $list[] = [
                    'user_id' => $item['user_id'],
                    'username' => $item['username'],
                    'nickname' => $item['nickname'],
                    'group_ids' => join(',', $groupIds),
                    'group_names' => join(',', $groupNames),
                    'is_group_access' => $item['is_group_access'],
                    'is_user_access' => $item['is_user_access'],
                    'is_system' => $item['is_system'],
                    'note' => $item['note'],
                    'status' => $item['status'],
                ];
            }
        }

        return [
            'total' => $data['pagination']['totalCount'],
            'list' => $list,
        ];
    }
1093417
protected function process_query(Query $query, array $columns = [], array $defaults = [])
	{
		// Count all items
		$all_items_count = $query->count();

		// Process incoming sorting values
		$sort = [];
		for ($i = 0; $i < \Input::param('iSortingCols'); $i++)
		{
			$sort[\Input::param('iSortCol_'.$i)] = \Input::param('sSortDir_'.$i);
		}

		$i = 0;
		$order_by = [];
		$where = [];
		$global_filter = \Input::param('sSearch');

		foreach ($columns as $key => $value)
		{
			$rels = explode('.', $key);

			$rel = '';

			for ($j=0; $j < count($rels) - 1 and count($rels) > 1; $j++)
			{
				$rel .= '.' . $rels[$j];
				$query->related($rel);
			}

			$value = \Arr::merge($defaults, $value);

			if ($eav = \Arr::get($value, 'eav', false))
			{
				$query->related($rel . '.' . $eav);
			}

			// Order by statement
			if (\Input::param('bSortable_'.$i, true) and \Arr::get($value, 'sort', true) and array_key_exists($i,  $sort))
			{
				$order_by[$key] = $sort[$i];
			}

			$filter = \Input::param('sSearch_'.$i);

			$filter = json_decode($filter);

			if ( ! in_array($filter, array(null, '', 'null')) and \Input::param('bSearchable_'.$i, true) and \Arr::get($value, 'search', true))
			{
				switch (\Arr::get($value, 'type', 'text'))
				{
					case 'select-multiple':
					case 'select':
					case 'enum':
						$query->where($key, 'IN', $filter);
						break;
					case 'select-single':
					case 'number':
						$query->where($key, $filter);
						break;
					case 'text':
						$query->where($key, 'LIKE', '%' . $filter . '%');
						break;
					case 'range':
						$query->where($key, 'BETWEEN', $filter);
						break;
					default:
						break;
				}
			}

			if ( ! empty($global_filter))
			{
				if (\Arr::get($value, 'search', true) === true and \Arr::get($value, 'global', true) === true)
				{
					$where[] = array($key, 'LIKE', '%' . $global_filter . '%');
				}
			}

			$i++;
		}

		if ( ! empty($where))
		{
			$query->where_open();
			foreach ($where as $where)
			{
				$query->or_where($where[0], $where[1], $where[2]);
			}
			$query->where_close();
		}

		// Order query
		$query->order_by($order_by);

		$partial_items_count = $query->count();

		// Limit query
		$query
			->limit(\Input::param('iDisplayLength', 10))
			->offset(\Input::param('iDisplayStart', 0));

		return array($all_items_count, $partial_items_count);
	}