Get the relation reference count.

@param \MwbExporter\Model\ForeignKey $fkey   The foreign key
@param int        $max    The maximum count
@return int
430947
protected function getRelationReferenceCount($fkey, $max = null)
    {
        $count = 0;
        $tablename = $fkey->getReferencedTable()->getRawTableName();
        foreach ($this->getTableM2MRelations() as $relation) {
            // $relation key => reference (ForeignKey), refTable (Table)
            if ($this->checkReferenceTableName($relation['refTable'], $tablename)) {
                $count++;
            }
            if ($max && $count == $max) {
                break;
            }
        }

        return $count;
    }
233000
public int countColumns(K key, SN start, SN end, int max) {
    SuperCountQuery<K, SN> query = HFactory.createSuperCountQuery(keyspace,
        keySerializer, topSerializer);
    query.setKey(key);
    query.setColumnFamily(columnFamily);
    query.setRange(start, end, max);
    return query.execute().get();
  }
31273
def get_relation_count_query(self, query, parent):
        
        query.select(QueryExpression('COUNT(*)'))

        other_key = self.wrap('%s.%s' % (query.get_model().get_table(), self._other_key))

        return query.where(self.get_qualified_foreign_key(), '=', QueryExpression(other_key))
316863
protected function belongsToMany($referenceModel, $foreignKey = null)
    {
        return (new Relations\BelongsToMany(
            new Relations\Maps\Inverse($this, $referenceModel, $foreignKey)
        ))->getResult();
    }
83486
public function relationCount(&$result, $relations, $aggregate = 'sum', $field = '*')
    {
        foreach ($relations as $key => $relation) {
            $closure = null;

            if ($relation instanceof \Closure) {
                $closure  = $relation;
                $relation = $key;
            } elseif (is_string($key)) {
                $name     = $relation;
                $relation = $key;
            }

            $relation = Db::parseName($relation, 1, false);
            $count    = $this->$relation()->relationCount($result, $closure, $aggregate, $field);

            if (!isset($name)) {
                $name = Db::parseName($relation) . '_' . $aggregate;
            }

            $result->setAttr($name, $count);
        }
    }
115845
protected function addUseRefFkQuery(&$script, ForeignKey $fk)
    {
        $fkTable = $this->getTable()->getDatabase()->getTable($fk->getTableName());
        $fkQueryBuilder = $this->getNewStubQueryBuilder($fkTable);
        $queryClass = $this->getClassNameFromBuilder($fkQueryBuilder, true);
        $relationName = $this->getRefFKPhpNameAffix($fk);
        $joinType = $this->getJoinType($fk);

        $this->addUseRelatedQuery($script, $fkTable, $queryClass, $relationName, $joinType);
    }
64057
public static function getTree($entity, $entityId, $maxLevel = null)
    {
        $query = static::find()
            ->alias('c')
            ->approved()
            ->andWhere([
                'c.entityId' => $entityId,
                'c.entity' => $entity,
            ])
            ->orderBy(['c.parentId' => SORT_ASC, 'c.createdAt' => SORT_ASC])
            ->with(['author']);

        if ($maxLevel > 0) {
            $query->andWhere(['<=', 'c.level', $maxLevel]);
        }

        $models = $query->all();

        if (!empty($models)) {
            $models = static::buildTree($models);
        }

        return $models;
    }
886779
public function getForeignKeyDDL(ForeignKey $fk)
    {
        if ($this->supportsForeignKeys($fk->getTable())) {
            return parent::getForeignKeyDDL($fk);
        }

        return '';
    }
157438
public function hasOne($entity, string $related, string $foreignKey = null, string $localKey = null): HasOne
    {
        $foreignKey = $foreignKey ?: $this->getForeignKey();

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

        $relatedMap = $relatedMapper->getEntityMap();

        $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->addSingleRelation($relation);
        $this->addForeignRelation($relation);
        $this->addNonProxyRelation($relation);

        // This relationship will always be eager loaded, as proxying it would
        // mean having an object that doesn't actually exists.
        if (!in_array($relation, $this->with)) {
            $this->with[] = $relation;
        }

        return new HasOne($relatedMapper, $entity, /*$relatedMap->getTable().'.'*/$foreignKey, $localKey);
    }
989961
public function addReferrer(ForeignKey $fk)
    {
        if ($this->referrers === null) {
            $this->referrers = array();
        }
        $this->referrers[] = $fk;
    }
94324
public function belongsTo($related, $foreignKey = null, $otherKey = null, $relation = null)
    {
        // If no relation name was given, we will use this debug backtrace to extract
        // the calling method's name and use that as the relationship name as most
        // of the time this will be what we desire to use for the relationships.
        if (is_null($relation)) {
            list($current, $caller) = debug_backtrace(false, 2);

            $relation = $caller['function'];
        }

        $specialType = $this->getCmsSpecialRelationType($relation);

        // If no foreign key was supplied, we can use a backtrace to guess the proper
        // foreign key name by using the name of the relationship function, which
        // when combined with an "_id" should conventionally match the columns.
        if (is_null($foreignKey)) {
            if ($specialType === self::RELATION_TYPE_CATEGORY) {
                $foreignKey = config('pxlcms.relations.categories.keys.category');
            } else {
                $foreignKey = Str::snake($relation);
            }
        }

        // If the relation name is the same (casing aside) as the foreign key attribute,
        // we must make sure that the foreign key property is at least a key in the
        // attributes array. If it is not, there will be recursive lookup problems
        // where the attribute is never resolved and 'property does not exist' exceptions occur.
        if (    snake_case($relation) == $foreignKey
            &&  ! array_key_exists($foreignKey, $this->attributes)
        ) {
            $this->attributes[ $foreignKey ] = null;
        }

        /** @var Builder $belongsTo */
        $belongsTo = parent::belongsTo($related, $foreignKey, $otherKey, $relation);

        // category relation must be filtered by module id
        if ($specialType === self::RELATION_TYPE_CATEGORY) {
            $belongsTo->where(
                config('pxlcms.relations.categories.keys.module'),
                $this->getModuleNumber()
            );
        }

        return $belongsTo;
    }
537573
protected function getForeignKeyCreate(array $output, string $fkName, array $fkData): array
    {
        $columns = "'" . $fkData['COLUMN_NAME'] . "'";
        $referencedTable = "'" . $fkData['REFERENCED_TABLE_NAME'] . "'";
        $referencedColumns = "'" . $fkData['REFERENCED_COLUMN_NAME'] . "'";
        $options = $this->getForeignKeyOptions($fkData, $fkName);

        $output[] = sprintf('%s->addForeignKey(%s, %s, %s, %s)', $this->ind2, $columns, $referencedTable, $referencedColumns, $options);

        return $output;
    }
469611
protected function addRefFKCount(&$script, ForeignKey $refFK)
    {
        $table = $this->getTable();
        $tblFK = $refFK->getTable();

        $peerClassname = $this->getStubPeerBuilder()->getClassname();

        $fkPeerBuilder = $this->getNewPeerBuilder($refFK->getTable());
        $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true);

        $collName = $this->getRefFKCollVarName($refFK);
        $lastCriteriaName = $this->getRefFKLastCriteriaVarName($refFK);

        $className = $fkPeerBuilder->getObjectClassname();

        $script .= "
    /**
     * Returns the number of related $className objects.
     *
     * @param      Criteria \$criteria
     * @param      boolean \$distinct
     * @param      PropelPDO \$con
     * @return int             Count of related $className objects.
     * @throws PropelException
     */
    public function count$relCol(Criteria \$criteria = null, \$distinct = false, PropelPDO \$con = null)
    {";

        $script .= "
        if (\$criteria === null) {
            \$criteria = new Criteria($peerClassname::DATABASE_NAME);
        } else {
            \$criteria = clone \$criteria;
        }

        if (\$distinct) {
            \$criteria->setDistinct();
        }

        \$count = null;

        if (\$this->$collName === null) {
            if (\$this->isNew()) {
                \$count = 0;
            } else {
";
        foreach ($refFK->getLocalColumns() as $colFKName) {
            // $colFKName is local to the referring table (i.e. foreign to this table)
            $lfmap = $refFK->getLocalForeignMapping();
            $localColumn = $this->getTable()->getColumn($lfmap[$colFKName]);
            $colFK = $refFK->getTable()->getColumn($colFKName);
            $clo = strtolower($localColumn->getName());
            $script .= "
                \$criteria->add(" . $fkPeerBuilder->getColumnConstant($colFK) . ", \$this->$clo);
";
        } // end foreach ($fk->getForeignColumns()

        $script .= "
                \$count = " . $fkPeerBuilder->getPeerClassname() . "::doCount(\$criteria, false, \$con);
            }
        } else {
            // criteria has no effect for a new object
            if (!\$this->isNew()) {
                // the following code is to determine if a new query is
                // called for.  If the criteria is the same as the last
                // one, just return count of the collection.
";
        foreach ($refFK->getLocalColumns() as $colFKName) {
            // $colFKName is local to the referring table (i.e. foreign to this table)
            $lfmap = $refFK->getLocalForeignMapping();
            $localColumn = $this->getTable()->getColumn($lfmap[$colFKName]);
            $colFK = $refFK->getTable()->getColumn($colFKName);
            $clo = strtolower($localColumn->getName());
            $script .= "

                \$criteria->add(" . $fkPeerBuilder->getColumnConstant($colFK) . ", \$this->$clo);
";
        } // foreach ($fk->getForeignColumns()
        $script .= "
                if (!isset(\$this->$lastCriteriaName) || !\$this->" . $lastCriteriaName . "->equals(\$criteria)) {
                    \$count = " . $fkPeerBuilder->getPeerClassname() . "::doCount(\$criteria, false, \$con);
                } else {
                    \$count = count(\$this->$collName);
                }
            } else {
                \$count = count(\$this->$collName);
            }
        }

        return \$count;
    }
";
    }
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)
977753
public function getDropForeignKeyDDL(ForeignKey $fk)
    {
        if ($fk->isSkipSql()) {
            return;
        }
        $pattern = "
ALTER TABLE %s DROP CONSTRAINT %s;
";

        return sprintf($pattern,
            $this->quoteIdentifier($fk->getTable()->getName()),
            $this->quoteIdentifier($fk->getName())
        );
    }
1002235
protected function addRefFKCount(&$script, ForeignKey $refFK)
    {
        $fkQueryClassName = $this->getClassNameFromBuilder($this->getNewStubQueryBuilder($refFK->getTable()));
        $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true);
        $collName = $this->getRefFKCollVarName($refFK);

        $joinedTableObjectBuilder = $this->getNewObjectBuilder($refFK->getTable());
        $className = $this->getClassNameFromBuilder($joinedTableObjectBuilder);

        $script .= "
    /**
     * Returns the number of related $className objects.
     *
     * @param      Criteria \$criteria
     * @param      boolean \$distinct
     * @param      ConnectionInterface \$con
     * @return int             Count of related $className objects.
     * @throws PropelException
     */
    public function count{$relCol}(Criteria \$criteria = null, \$distinct = false, ConnectionInterface \$con = null)
    {
        \$partial = \$this->{$collName}Partial && !\$this->isNew();
        if (null === \$this->$collName || null !== \$criteria || \$partial) {
            if (\$this->isNew() && null === \$this->$collName) {
                return 0;
            }

            if (\$partial && !\$criteria) {
                return count(\$this->get$relCol());
            }

            \$query = $fkQueryClassName::create(null, \$criteria);
            if (\$distinct) {
                \$query->distinct();
            }

            return \$query
                ->filterBy" . $this->getFKPhpNameAffix($refFK) . "(\$this)
                ->count(\$con);
        }

        return count(\$this->$collName);
    }
";
    }
260117
private function _getRelatedFks($data, $relation, $modelClass)
    {
        $fks = [];
        if (is_array($data)) {
            // Get the right link definition
            if ($relation->via instanceof BaseActiveRecord) {
                $link = $relation->via->link;
            } elseif (is_array($relation->via)) {
                list($viaName, $viaQuery) = $relation->via;
                $link = $viaQuery->link;
            } else {
                $link = $relation->link;
            }
            // search PK
            foreach ($modelClass::primaryKey() as $modelAttribute) {
                if (isset($data[$modelAttribute])) {
                    $fks[$modelAttribute] = $data[$modelAttribute];
                } elseif ($relation->multiple && !$relation->via) {
                    foreach ($link as $relatedAttribute => $relatedModelAttribute) {
                        if (!isset($data[$relatedAttribute]) && in_array($relatedAttribute, $modelClass::primaryKey())) {
                            $fks[$relatedAttribute] = $this->owner->{$relatedModelAttribute};
                        }
                    }
                } else {
                    $fks = [];
                    break;
                }
            }
            if (empty($fks)) {
                foreach ($link as $relatedAttribute => $modelAttribute) {
                    if (isset($data[$modelAttribute])) {
                        $fks[$modelAttribute] = $data[$modelAttribute];
                    }
                }
            }
        } else {
            $fks = $data;
        }
        return $fks;
    }