Add a relationship count condition to the query.

@param  string  $relation
@param  string  $operator
@param  int     $count
@param  string  $boolean
@param  \Closure  $callback
@return \Fly\Database\ActiveRecord\Builder|static
774682
public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', $callback = null)
	{
		$relation = $this->getHasRelationQuery($relation);

		$query = $relation->getRelationCountQuery($relation->getRelated()->newQuery(), $this);

		if ($callback) call_user_func($callback, $query);

		return $this->addHasWhere($query, $relation, $operator, $count, $boolean);
	}
1326257
public function getRelationCountQuery(Builder $query, Builder $parent)
    {
        return $this->getRelationExistenceQuery($query, $parent, new Expression('count(*)'));
    }
213098
public function countBy($callback = null)
    {
        if (is_null($callback)) {
            $callback = function ($value) {
                return $value;
            };
        }

        return new static($this->groupBy($callback)->map(function ($value) {
            return $value->count();
        }));
    }
1057377
public function getRelationCountQuery(Builder $query, Builder $parent)
	{
		return $this->getRelationQuery($query, $parent, new Expression('count(*)'));
	}
683554
function with(array $relations, array $where = null, $order = null, $limit = 0, $offset = 0) {
		$qthis = $this->conn->quoteName($this->getName());
		$query = $this->getQueryWriter()->reset();
		$query->write("SELECT", "$qthis.*", "FROM", $qthis);
		foreach ($relations as $relation) {
			if (!($relation instanceof Table\Reference)) {
				$relation = static::resolve($relation)->getRelation($this->getName());
			}
			if ($this->getName() === $relation->foreignTable) {
				$query->write("JOIN", $relation->referencedTable)->write("ON");
				foreach ($relation as $key => $ref) {
					$query->criteria(
						array(
							"{$relation->referencedTable}.{$ref}=" => 
								new QueryExpr("{$relation->foreignTable}.{$key}")
						)
					);
				}
			} else {
				$query->write("JOIN", $relation->foreignTable)->write("ON");
				foreach ($relation as $key => $ref) {
					$query->criteria(
						array(
							"{$relation->referencedTable}.{$ref}=" => 
								new QueryExpr("{$relation->foreignTable}.{$key}")
						)
					);
				}
			}
		}
		if ($where) {
			$query->write("WHERE")->criteria($where);
		}
		if ($order) {
			$query->write("ORDER BY", $order);
		}
		if ($limit) {
			$query->write("LIMIT", $limit);
		}
		if ($offset) {
			$query->write("OFFSET", $offset);
		}
		return $this->execute($query);
	}
109150
public function withCount($relations) {
        if (empty($relations)) {
            return $this;
        }

        if (empty($this->selects)) {
            $this->select();
        }

        $relations = is_array($relations) ? $relations : func_get_args();

        foreach ($this->parseWithRelations($relations) as $name => $constraints) {
            // First we will determine if the name has been aliased using an "as" clause on the name
            // and if it has we will extract the actual relationship name and the desired name of
            // the resulting column. This allows multiple counts on the same relationship name.
            $segments = explode(' ', $name);

            $alias = null;

            if (count($segments) == 3 && strtolower($segments[1]) == 'as') {
                list($name, $alias) = [$segments[0], $segments[2]];
            }

            $relation = $this->getRelationWithoutConstraints($name);

            // Here we will get the relationship count query and prepare to add it to the main query
            // as a sub-select. First, we'll get the "has" query and use that to get the relation
            // count query. We will normalize the relation name then append _count as the name.
            $query = $relation->getRelationExistenceCountQuery(
                $relation->getRelated()->query(), $this
            );

            // Finally we will add the proper result column alias to the query and run the subselect
            // statement against the query builder. Then we will return the builder instance back
            // to the developer for further constraint chaining that needs to take place on it.
            $column = $alias ?: strtolower($name.'_count');

            $this->selectSub($query->getSql(), $column);
        }

        return $this;
    }
304032
protected function isCountableRelation($relation)
    {
        return is_a($relation, BelongsToMany::class)
            || is_a($relation, HasMany::class)
            || is_a($relation, HasManyThrough::class);
    }
584038
public static function countWhere (string $column, array $operatorValue, string $joinOperator="AND") : int
	{
		$joinOperator 	= static::validateOperator($joinOperator, "AND");
		$expression 	= static::generateValue($column, $operatorValue, $joinOperator);
		$sqlQuery  		= "SELECT COUNT(*) as count FROM ".static::$tableName." WHERE {$column} {$expression}";
		$resultSet 		= Database::getInstance()->query($sqlQuery);
		$row 			= Database::fetchAssoc($resultSet);
		return (int) array_shift($row);
	}
287598
public function eagerlyResult(&$result, $relation, $subRelation, $closure)
    {
        $pk = $result->getPk();

        if (isset($result->$pk)) {
            $key   = $result->$pk;
            $where = [
                [$this->morphKey, '=', $key],
                [$this->morphType, '=', $this->type],
            ];
            $data = $this->eagerlyMorphToMany($where, $relation, $subRelation, $closure);

            if (!isset($data[$key])) {
                $data[$key] = [];
            }

            foreach ($data[$key] as &$relationModel) {
                $relationModel->setParent(clone $result);
                $relationModel->isUpdate(true);
            }

            $result->setRelation(Db::parseName($relation), $this->resultSetBuild($data[$key]));
        }
    }
872354
def get_relation_count_query(self, query, parent):
        
        parent_table = self._parent.get_table()

        self._set_join(query)

        query.select(QueryExpression('COUNT(*)'))

        key = self.wrap('%s.%s' % (parent_table, self._first_key))

        return query.where(self.get_has_compare_key(), '=', QueryExpression(key))
1027332
def get_relation_count_query(self, query, parent):
        
        if parent.get_query().from__ == query.get_query().from__:
            return self.get_relation_count_query_for_self_join(query, parent)

        self._set_join(query)

        return super(BelongsToMany, self).get_relation_count_query(query, parent)
817710
public function on($column1, $column2 = null, $operator = '=')
    {
        return $this->addJoinCondition($column1, $column2, $operator);
    }
1104985
protected function returnRelation($relation, $entity, callable $callback = null, $alias = null)
    {
        if (is_string($entity)) {
            $entity = Reflect::create($entity, ['alias' => $alias]);
        }

        $relation = new $relation($this, $entity);

        if ($alias) {
            $relation->getRightEntity()->setAlias($alias);
        }

        if ($callback) {
            $callback($relation);
        }

        return $relation;
    }
261995
public static function validateToOneRelation($relation, $relationship)
    {
        if (
            !is_null($relation)
            && !$relation instanceof ResourceEntityInterface
        ) {
            $type = is_object($relation)
                ? get_class($relation) : gettype($relation);
            throw new \Exception(sprintf(
                self::ERROR_NOT_RESOURCE_ENTITY, $relationship, $type
            ));
        }
    }
37289
public function has($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null)
    {
        if (strpos($relation, '.') !== false) {
            return $this->hasNested($relation, $operator, $count, $boolean, $callback);
        }

        $relation = $this->getHasRelationQuery($relation);

        $query = $relation->getRelationCountQuery($relation->getRelated()->newQuery(), $this);

        if ($callback) call_user_func($callback, $query);

        return $this->addHasWhere($query, $relation, $operator, $count, $boolean);
    }
5672
public function withCount( $relations )
	{
		if ( is_null( $this->query->columns ) )
		{
			$this->query->select( ['*'] );
		}

		$relations = is_array( $relations ) ? $relations : func_get_args();

		foreach ( $this->parseWithRelations( $relations ) as $name => $constraints )
		{
			// Here we will get the relationship count query and prepare to add it to the main query
			// as a sub-select. First, we'll get the "has" query and use that to get the relation
			// count query. We will normalize the relation name then append _count as the name.
			$relation = $this->getHasRelationQuery( $name );

			$query = $relation->getRelationCountQuery( $relation->getRelated()->newQuery(), $this );

			$query->callScope( $constraints );

			$query->mergeModelDefinedRelationConstraints( $relation->getQuery() );

			$this->selectSub( $query->toBase(), snake_case( $name ) . '_count' );
		}

		return $this;
	}
654918
public function has($relation, $operator = '>=', $count = 1)
    {
        $this->hasRelations[$relation] = [$operator, $count];

        return $this;
    }