Query places.

@param string $what
@param string $fact
@param int    $parent
@param bool   $country

@return int[]|stdClass[]
549405
public function statsPlaces(string $what = 'ALL', string $fact = '', int $parent = 0, bool $country = false): array
    {
        if ($fact) {
            return $this->queryFactPlaces($fact, $what, $country);
        }

        $query = DB::table('places')
            ->join('placelinks', static function (JoinClause $join): void {
                $join->on('pl_file', '=', 'p_file')
                    ->on('pl_p_id', '=', 'p_id');
            })
            ->where('p_file', '=', $this->tree->id());

        if ($parent > 0) {
            // Used by placehierarchy map modules
            $query->select(['p_place AS place'])
                ->selectRaw('COUNT(*) AS tot')
                ->where('p_id', '=', $parent)
                ->groupBy(['place']);
        } else {
            $query->select(['p_place AS country'])
                ->selectRaw('COUNT(*) AS tot')
                ->where('p_parent_id', '=', 0)
                ->groupBy(['country'])
                ->orderByDesc('tot')
                ->orderBy('country');
        }

        if ($what === 'INDI') {
            $query->join('individuals', static function (JoinClause $join): void {
                $join->on('pl_file', '=', 'i_file')
                    ->on('pl_gid', '=', 'i_id');
            });
        } elseif ($what === 'FAM') {
            $query->join('families', static function (JoinClause $join): void {
                $join->on('pl_file', '=', 'f_file')
                    ->on('pl_gid', '=', 'f_id');
            });
        }

        return $query->get()->all();
    }
62869
public function getInfoWithMultipleWhere($wheres = '', $field = 'id', $selectField = NULL)
    {
        if (is_array($wheres) && count($wheres) > 0) {
            foreach ($wheres as $key => $value) {
                if (is_array($value['value'])) {
                    $this->db->where($value['field'], $value['value'], self::OPERATOR_IS_IN);
                } else {
                    $this->db->where($value['field'], $value['value'], $value['operator']);
                }
            }
        } else {
            $this->db->where($field, $wheres, self::OPERATOR_EQUAL_TO);
        }
        $result = $this->db->getOne($this->table, $selectField);
        if ($this->db->count > 0) {
            return $result;
        }

        return NULL;
    }
574
public function findWhere($conditions=null, $_=null)
    {
        $query =  $this->db->select($this->getColumns())
            ->from($this->entity->getTable());
        $query->context->resultHandler = function ($result){
            foreach ($result as &$i){
                $i = $this->entity->make($i, false);
            }
            return $result;
        };
        return call_user_func_array([$query, 'where'], func_get_args());
    }
193171
public function administrativeAreas($country_id, Request $request = null)
    {
        $query = AdministrativeArea::where('country_id', $country_id)
            ->with('country');

        if ($request) {
            $resource = new Collection($query, 'administrative_area', $request);
            return $this->respondWithCollection($resource);
        }
        return $query->get();
    }
212049
protected function query($query, $where = null, $size = null, $offset = null)
    {
        $params = [];

        if (is_array($where)) {
            $conditions = [];
            foreach($where as $column => $value) {
                $placeholder = '?';
                $value = '' . $value;

                $conditions[] = $column . ' = ' . $placeholder;
                $params[] = $value;
            }
            if (count($conditions)) {
                $query .= ' WHERE ' . implode(' AND ', $conditions);
            }
        }

        if (!is_null($size)) {
            $query = $this->getPersistence()->getPlatForm()->limitStatement($query, $size, $offset);
        }

        return $this->getPersistence()->query($query, $params);
    }
1199827
function Load($where=null,$bindarr=false)
	{
		$db = $this->DB();
		if (!$db) {
			return false;
		}
		$this->_where = $where;

		$save = $db->SetFetchMode(ADODB_FETCH_NUM);
		$qry = "select * from ".$this->_table;
		$table =& $this->TableInfo();

		if(($k = reset($table->keys))) {
			$hasManyId   = $k;
		}
		else {
			$hasManyId   = 'id';
		}

		foreach($table->_belongsTo as $foreignTable) {
			if(($k = reset($foreignTable->TableInfo()->keys))) {
				$belongsToId = $k;
			}
			else {
				$belongsToId = 'id';
			}
			$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
				$this->_table.'.'.$foreignTable->foreignKey.'='.
				$foreignTable->_table.'.'.$belongsToId;
		}
		foreach($table->_hasMany as $foreignTable)
		{
			$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
				$this->_table.'.'.$hasManyId.'='.
				$foreignTable->_table.'.'.$foreignTable->foreignKey;
		}
		if($where) {
			$qry .= ' WHERE '.$where;
		}

		// Simple case: no relations. Load row and return.
		if((count($table->_hasMany) + count($table->_belongsTo)) < 1) {
			$row = $db->GetRow($qry,$bindarr);
			if(!$row) {
				return false;
			}
			$db->SetFetchMode($save);
			return $this->Set($row);
		}

		// More complex case when relations have to be collated
		$rows = $db->GetAll($qry,$bindarr);
		if(!$rows) {
			return false;
		}
		$db->SetFetchMode($save);
		if(count($rows) < 1) {
			return false;
		}
		$class = get_class($this);
		$isFirstRow = true;

		if(($k = reset($this->TableInfo()->keys))) {
			$myId   = $k;
		}
		else {
			$myId   = 'id';
		}
		$index = 0; $found = false;
		/** @todo Improve by storing once and for all in table metadata */
		/** @todo Also re-use info for hasManyId */
		foreach($this->TableInfo()->flds as $fld) {
			if($fld->name == $myId) {
				$found = true;
				break;
			}
			$index++;
		}
		if(!$found) {
			$this->outp_throw("Unable to locate key $myId for $class in Load()",'Load');
		}

		foreach($rows as $row) {
			$rowId = intval($row[$index]);
			if($rowId > 0) {
				if($isFirstRow) {
					$isFirstRow = false;
					if(!$this->Set($row)) {
						return false;
					}
				}
				$obj = new $class($table,false,$db);
				$obj->Set($row);
				// TODO Copy/paste code below: bad!
				if(count($table->_hasMany) > 0) {
					foreach($table->_hasMany as $foreignTable) {
						$foreignName = $foreignTable->foreignName;
						if(!empty($obj->$foreignName)) {
							if(!is_array($this->$foreignName)) {
								$foreignObj = $this->$foreignName;
								$this->$foreignName = array(clone($foreignObj));
							}
							else {
								$foreignObj = $obj->$foreignName;
								array_push($this->$foreignName, clone($foreignObj));
							}
						}
					}
				}
				if(count($table->_belongsTo) > 0) {
					foreach($table->_belongsTo as $foreignTable) {
						$foreignName = $foreignTable->foreignName;
						if(!empty($obj->$foreignName)) {
							if(!is_array($this->$foreignName)) {
								$foreignObj = $this->$foreignName;
								$this->$foreignName = array(clone($foreignObj));
							}
							else {
								$foreignObj = $obj->$foreignName;
								array_push($this->$foreignName, clone($foreignObj));
							}
						}
					}
				}
			}
		}
		return true;
	}
72641
protected function setWhere()
    {
        $foreign = $this->getForeignKey();

        $parentKey = $this->parentMap->getKeyName();

        $this->query->where($foreign, '=', $this->parent->getEntityAttribute($parentKey));

        return $this;
    }
509009
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
    {
        $table = $this->getParent()->getTable();
        $query = parent::getRelationQuery($query, $parent, $columns);

        return $query->where("{$table}.{$this->morphType}", '=', $this->morphName);
    }
529087
def _merge_wheres_to_has(self, has_query, relation):
        
        relation_query = relation.get_base_query()

        has_query.merge_wheres(relation_query.wheres, relation_query.get_bindings())

        self._query.merge_bindings(has_query.get_query())
350251
protected function addNestedWhereSlice( QueryBuilder $query, $wheres, $offset, $length = null )
	{
		$whereSlice = array_slice( $wheres, $offset, $length );

		$whereBooleans = collect( $whereSlice )->pluck( 'boolean' );

		// Here we'll check if the given subset of where clauses contains any "or"
		// booleans and in this case create a nested where expression. That way
		// we don't add any unnecessary nesting thus keeping the query clean.
		if ( $whereBooleans->contains( 'or' ) )
		{
			$query->wheres[] = $this->nestWhereSlice( $whereSlice );
		}
		else
		{
			$query->wheres = array_merge( $query->wheres, $whereSlice );
		}
	}
865063
public function find($where = [], $prefix = 'u', $justCount = false, $joinConditions = [])
    {
        $searchPattern = $this->helper->getSearchPattern();
        $searchFields = $this->helper->getSearchFields();

        // if search string is set, but search fields are not, take all fields into account
        if (!is_null($searchPattern) && '' != $searchPattern && (is_null($searchFields) || 0 == count($searchFields))) {
            $searchFields = $this->getEntityManager()->getClassMetadata($this->getEntityName())->getFieldNames();
        }

        $textFields = $this->getFieldsWitTypes(['text', 'string', 'guid'], $searchFields);
        if (is_numeric($searchPattern)) {
            $numberFields = $this->getFieldsWitTypes(['integer', 'float', 'decimal'], $searchFields);
        } else {
            $numberFields = [];
        }

        $queryBuilder = new ListQueryBuilder(
            $this->getClassMetadata()->getAssociationNames(),
            $this->getClassMetadata()->getFieldNames(),
            $this->getEntityName(),
            $this->helper->getFields(),
            $this->helper->getSorting(),
            $where,
            $textFields,
            $numberFields,
            $joinConditions
        );

        if ($justCount) {
            $queryBuilder->justCount('u.id');
        }

        $dql = $queryBuilder->find($prefix);

        $query = $this->getEntityManager()
            ->createQuery($dql);

        if (!$justCount) {
            $query->setFirstResult($this->helper->getOffset())
                ->setMaxResults($this->helper->getLimit());
        }
        if (null != $searchPattern && '' != $searchPattern) {
            if (count($searchFields) > 0) {
                if (count($textFields) > 0) {
                    $query->setParameter('search', '%' . $searchPattern . '%');
                }
                if (count($numberFields) > 0) {
                    $query->setParameter('strictSearch', $searchPattern);
                }
            }
        }

        // if just used for counting
        if ($justCount) {
            return intval($query->getSingleResult()['totalcount']);
        }

        $results = $query->getArrayResult();

        // check if relational filter was set ( e.g. emails[0]_email)
        // and filter result
        if (count($filters = $queryBuilder->getRelationalFilters()) > 0) {
            $filteredResults = [];
            // check if fields do contain id, else skip
            if (count($fields = $this->helper->getFields()) > 0 && false !== array_search('id', $fields)) {
                $ids = [];
                foreach ($results as $result) {
                    $id = $result['id'];
                    // check if result already in resultset
                    if (!array_key_exists($id, $ids)) {
                        $ids[$id] = -1;
                        $filteredResults[] = $result;
                    }
                    ++$ids[$id];
                    // check filters
                    foreach ($filters as $filter => $key) {
                        // check if we are at the specified index
                        if ($key == $ids[$id]) {
                            $index = $this->getArrayIndexByKeyValue($filteredResults, $id);
                            // set to current key
                            $filteredResults[$index][$filter] = $result[$filter];
                        }
                    }
                }
                $results = $filteredResults;
            }
        }

        return $results;
    }
936704
public function getDatabaseRelations(Where $where = null)
    {
        $where = Where::create('n.nspname !~* $*', ['^pg_'])
            ->andWhere('n.nspname != $*', ['information_schema'])
            ->andWhere($where)
            ;

        return $this->getRelations($where);
    }
1101560
public function countWhere($where, array $values = [])
    {
        $sql = sprintf(
            "select count(*) as result from %s where :condition",
            $this->getStructure()->getRelation()
        );

        return $this->fetchSingleValue($sql, $where, $values);
    }
925681
public static function formatFactPlaceShort(\Fisharebest\Webtrees\Fact $fact, $format, $anchor=false){
		$html='';
		
		if ($fact === null) return $html;
		$place = $fact->getPlace();
		if($place){
			$dplace = new Place($place);
			$html .= $dplace->htmlFormattedName($format, $anchor);
		}
		return $html;
	}
145911
public function getAreaForCountry(Country $country)
    {
        $area = null;

        if (null !== $areaDeliveryModule = AreaDeliveryModuleQuery::create()->findByCountryAndModule(
            $country,
            $this->getModuleModel()
        )) {
            $area = $areaDeliveryModule->getArea();
        }

        return $area;
    }
529167
protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice)
    {
        $whereBooleans = collect($whereSlice)->pluck('boolean');

        // Here we'll check if the given subset of where clauses contains any "or"
        // booleans and in this case create a nested where expression. That way
        // we don't add any unnecessary nesting thus keeping the query clean.
        if ($whereBooleans->contains('or')) {
            $query->wheres[] = $this->createNestedWhere(
                $whereSlice, $whereBooleans->first()
            );
        } else {
            $query->wheres = array_merge($query->wheres, $whereSlice);
        }
    }
395176
public function fetchArray($result_object,$which_connection='')
    {
        if (is_null($result_object)) return false;
        if ($result_object === false) return false;

        if ($which_connection == '') {
            $which_connection = $this->default_db;
        }
        $ret = $result_object->fields;
        if ($result_object) {
            $result_object->MoveNext();
        }

        return $ret;
    }