General query on ages.

@param string $related
@param string $sex
@param int    $year1
@param int    $year2

@return array|string
195658
public function statsAgeQuery(string $related = 'BIRT', string $sex = 'BOTH', int $year1 = -1, int $year2 = -1)
    {
        $prefix = DB::connection()->getTablePrefix();

        $query = $this->birthAndDeathQuery($sex);

        if ($year1 >= 0 && $year2 >= 0) {
            $query
                ->whereIn('birth.d_type', ['@#DGREGORIAN@', '@#DJULIAN@'])
                ->whereIn('death.d_type', ['@#DGREGORIAN@', '@#DJULIAN@']);

            if ($related === 'BIRT') {
                $query->whereBetween('birth.d_year', [$year1, $year2]);
            } elseif ($related === 'DEAT') {
                $query->whereBetween('death.d_year', [$year1, $year2]);
            }
        }

        return $query
            ->select(DB::raw($prefix . 'death.d_julianday2 - ' . $prefix . 'birth.d_julianday1 AS days'))
            ->orderBy('days', 'desc')
            ->get()
            ->all();
    }
657892
public function yearArray($begin, $end)
    {
        $dateArray = array();
        for ($i = $begin; $i <= $end; ++$i) {
            $dateArray[] = $i;
        }
        return $dateArray;
    }
808215
public function getRelativeYearCount($end = null, $locale = null, $query = null, $cacheKey = null)
    {
        if (is_null($end))
        {
            $end = Carbon::today();
        }

        return $this->getCountInBetween($end->copy()->subYear()->startOfDay(), $end->endOfDay(), $locale, $query, $cacheKey);
    }
861208
public function getRelationshipType($to)
    {
        $map = $this->relationshipTypeMap;
        if (isset($map[$to])) {
            return $map[$to];
        }

        return false;
    }
461424
private function ageBetweenSiblingsName(int $total): string
    {
        $rows = $this->ageBetweenSiblingsQuery($total);

        foreach ($rows as $fam) {
            $family = Family::getInstance($fam->family, $this->tree);
            $child1 = Individual::getInstance($fam->ch1, $this->tree);
            $child2 = Individual::getInstance($fam->ch2, $this->tree);

            if ($child1->canShow() && $child2->canShow()) {
                $return = '<a href="' . e($child2->url()) . '">' . $child2->fullName() . '</a> ';
                $return .= I18N::translate('and') . ' ';
                $return .= '<a href="' . e($child1->url()) . '">' . $child1->fullName() . '</a>';
                $return .= ' <a href="' . e($family->url()) . '">[' . I18N::translate('View this family') . ']</a>';
            } else {
                $return = I18N::translate('This information is private and cannot be shown.');
            }

            return $return;
        }

        return '';
    }
1244639
public static function getActivityRelatedEntity($data) {
    $related_object = $data['related_object'][0];

    // We return parent comment as related object as comment
    // for create_comment_reply messages.
    if ($data['message_template'] === 'create_comment_reply') {
      $comment_storage = \Drupal::entityTypeManager()->getStorage('comment');
      // @TODO: Check if comment published?
      $comment = $comment_storage->load($related_object['target_id']);
      $parent_comment = $comment->getParentComment();
      if (!empty($parent_comment)) {
        $related_object = [
          'target_type' => $parent_comment->getEntityTypeId(),
          'target_id' => $parent_comment->id(),
        ];
      }
    }
    // We return commented entity as related object for all other comments.
    elseif (isset($related_object['target_type']) && $related_object['target_type'] === 'comment') {
      $comment_storage = \Drupal::entityTypeManager()->getStorage('comment');
      // @todo: Check if comment published?
      $comment = $comment_storage->load($related_object['target_id']);
      if ($comment) {
        $commented_entity = $comment->getCommentedEntity();
        if (!empty($commented_entity)) {
          $related_object = [
            'target_type' => $commented_entity->getEntityTypeId(),
            'target_id' => $commented_entity->id(),
          ];
        }
      }
    }
    // We return Event as related object for all Event Enrollments.
    elseif (isset($related_object['target_type']) && $related_object['target_type'] === 'event_enrollment') {
      $entity_storage = \Drupal::entityTypeManager()
        ->getStorage($related_object['target_type']);
      $entity = $entity_storage->load($related_object['target_id']);

      /** @var \Drupal\social_event\Entity\EventEnrollment $entity */
      $event_id = $entity->getFieldValue('field_event', 'target_id');
      if (!empty($event_id)) {
        $related_object = [
          'target_type' => 'node',
          'target_id' => $event_id,
        ];
      }
    }
    return $related_object;
  }
709037
public function belongsToThrough($related, $through, $localKey = null, $prefix = '', $foreignKeyLookup = [])
    {
        /** @var \Illuminate\Database\Eloquent\Model $relatedInstance */
        $relatedInstance = new $related;
        $throughParents = [];
        $foreignKeys = [];

        foreach ((array) $through as $model) {
            $foreignKey = null;

            if (is_array($model)) {
                $foreignKey = $model[1];

                $model = $model[0];
            }

            /** @var \Illuminate\Database\Eloquent\Model $instance */
            $instance = new $model;

            if ($foreignKey) {
                $foreignKeys[$instance->getTable()] = $foreignKey;
            }

            $throughParents[] = $instance;
        }

        foreach ($foreignKeyLookup as $model => $foreignKey) {
            $instance = new $model;

            if ($foreignKey) {
                $foreignKeys[$instance->getTable()] = $foreignKey;
            }
        }

        return $this->newBelongsToThrough($relatedInstance->newQuery(), $this, $throughParents, $localKey, $prefix, $foreignKeys);
    }
916167
private function getRelationships()
    {
        $r = '';

        $relationships = (array)$this->xml->xpath('/draggy/relationships/relation');

        foreach ($relationships as $relation) {
            $relationAttributes = (array)$relation;
            $relationAttributes = $relationAttributes['@attributes'];

            $this->checkMandatoryAttributes('Relationship', $relationAttributes, ['from', 'to', 'type']);

            $r .= 'var l = new Link(\'' . str_replace(
                '\\',
                '\\\\',
                $relationAttributes['from']
            ) . '\',\'' . str_replace(
                '\\',
                '\\\\',
                $relationAttributes['to']
            ) . '\',\'' . $relationAttributes['type'] . '\',' . ( isset( $relationAttributes['fromAttribute'] ) ? '\'' . $relationAttributes['fromAttribute'] . '\'' : 'undefined' ) . ', ' . ( isset( $relationAttributes['toAttribute'] ) ? '\'' . $relationAttributes['toAttribute'] . '\'' : 'undefined' ) . ')' . PHP_EOL;

            if (isset( $relationAttributes['broken'] )) {
                $r .= 'l.setBroken(' . $relationAttributes['broken'] . ');' . PHP_EOL;
            }

            if (isset( $relationAttributes['persist'] )) {
                if ('true' === $relationAttributes['persist']) { // Backwards compatibility
                    $relationAttributes['persist'] = 'both';
                }

                $r .= 'l.setPersist("' . $relationAttributes['persist'] . '");' . PHP_EOL;
            } else { // Backwards compatibility
                $r .= 'l.setPersist(true);' . PHP_EOL;
            }

            if (isset( $relationAttributes['remove'] )) {
                if ('true' === $relationAttributes['remove']) { // Backwards compatibility
                    $relationAttributes['remove'] = 'both';
                }
                $r .= 'l.setRemove("' . $relationAttributes['remove'] . '");' . PHP_EOL;
            } else { // Backwards compatibility
                $r .= 'l.setRemove(true);' . PHP_EOL;
            }
        }

        return $r;
    }
139283
public function age($date1, $date2 = null)
    {
        $formatter = new AgeFormatter();

        return $formatter->formatDate($date1, $date2);
    }
473552
public function hasMany($related, $parentKey = null, $localKey = null)
    {
        $parentKey = $parentKey ?: $this->getParentKey();
        $localKey = $localKey ?: $this->getKeyName();

        $instance = new $related;

        return new Relations\Relation($instance, $this, $parentKey, $localKey);
    }
312309
public function byYears(int $years): Date
    {
        return $this->yearTo($this->originalDate->year() + $years);
    }
1143708
public function hasMany($entity, string $related, string $foreignKey = null, string $localKey = null): HasMany
    {
        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $relatedMapper = Manager::getInstance()->mapper($related);

        $localKey = $localKey ?: $this->getKeyName();

        // Add the relation to the definition in map
        list(, $caller) = debug_backtrace(false);
        $relation = $caller['function'];
        $this->relatedClasses[$relation] = $related;

        $this->addManyRelation($relation);
        $this->addForeignRelation($relation);

        return new HasMany($relatedMapper, $entity, $foreignKey, $localKey);
    }
577897
public static function cousinName2(int $n, string $sex, string $relation): string
    {
        if ($sex === 'M') {
            switch ($n) {
                case 1:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('MALE', 'first %s', $relation);
                case 2:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('MALE', 'second %s', $relation);
                case 3:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('MALE', 'third %s', $relation);
                case 4:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('MALE', 'fourth %s', $relation);
                case 5:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('MALE', 'fifth %s', $relation);
                default:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('MALE', '%1$s × %2$s', I18N::number($n), $relation);
            }
        }

        if ($sex === 'F') {
            switch ($n) {
                case 1:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('FEMALE', 'first %s', $relation);
                case 2:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('FEMALE', 'second %s', $relation);
                case 3:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('FEMALE', 'third %s', $relation);
                case 4:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('FEMALE', 'fourth %s', $relation);
                case 5:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('FEMALE', 'fifth %s', $relation);
                default:
                    /* I18N: A Spanish relationship name, such as third great-nephew */
                    return I18N::translateContext('FEMALE', '%1$s × %2$s', I18N::number($n), $relation);
            }
        }

        switch ($n) {
            case 1:
                /* I18N: A Spanish relationship name, such as third great-nephew */
                return I18N::translate('first %s', $relation);
            case 2:
                /* I18N: A Spanish relationship name, such as third great-nephew */
                return I18N::translate('second %s', $relation);
            case 3:
                /* I18N: A Spanish relationship name, such as third great-nephew */
                return I18N::translate('third %s', $relation);
            case 4:
                /* I18N: A Spanish relationship name, such as third great-nephew */
                return I18N::translate('fourth %s', $relation);
            case 5:
                /* I18N: A Spanish relationship name, such as third great-nephew */
                return I18N::translate('fifth %s', $relation);
            default:
                /* I18N: A Spanish relationship name, such as third great-nephew */
                return I18N::translate('%1$s × %2$s', I18N::number($n), $relation);
        }
    }
1134791
public function hasMany($related, $foreignKey = null, $localKey = null)
    {
        $this->htmlType('select');
        $args = func_get_args();
        $args['type'] = 'hasMany';
        return $this->setRelationship(json_encode($args));
    }
441969
public function statsMarriageQuery(int $year1 = -1, int $year2 = -1): Builder
    {
        $query = DB::table('dates')
            ->where('d_file', '=', $this->tree->id())
            ->where('d_fact', '=', 'MARR')
            ->select(['d_month', DB::raw('COUNT(*) AS total')])
            ->groupBy('d_month');

        if ($year1 >= 0 && $year2 >= 0) {
            $query->whereBetween('d_year', [$year1, $year2]);
        }

        return $query;
    }
1093961
protected function hasOneOrManyDeep($related, array $through, array $foreignKeys, array $localKeys)
    {
        /** @var \Illuminate\Database\Eloquent\Model $relatedInstance */
        $relatedInstance = $this->newRelatedInstance($related);

        $throughParents = $this->hasOneOrManyDeepThroughParents($through);

        $foreignKeys = $this->hasOneOrManyDeepForeignKeys($relatedInstance, $throughParents, $foreignKeys);

        $localKeys = $this->hasOneOrManyDeepLocalKeys($relatedInstance, $throughParents, $localKeys);

        return [$relatedInstance->newQuery(), $this, $throughParents, $foreignKeys, $localKeys];
    }
509519
public function getRelationsByChild($childrenIds)
    {
        $metadata      = $this->getEntityMetaData(\Magento\Catalog\Api\Data\ProductInterface::class);
        $entityTable   = $this->getTable($metadata->getEntityTable());
        $relationTable = $this->getTable('catalog_product_relation');
        $joinCondition = sprintf('relation.parent_id = entity.%s', $metadata->getLinkField());

        $select = $this->getConnection()->select()
            ->from(['relation' => $relationTable], [])
            ->join(['entity' => $entityTable], $joinCondition, [$metadata->getIdentifierField()])
            ->where('child_id IN(?)', array_map('intval', $childrenIds));

        return $this->getConnection()->fetchCol($select);
    }