Get the child rows of a row by foreign key
@param \pq\Gateway\Row $foreign
@param string $ref optional fkey name
@param string $order
@param int $limit
@param int $offset
@return mixed
429392
function of(Row $foreign, $ref = null, $order = null, $limit = 0, $offset = 0) {
		// select * from $this where $this->$foreignColumn = $foreign->$referencedColumn
		
		if (!($rel = $this->getRelation($foreign->getTable()->getName(), $ref))) {
			return $this->onResult(null);
		}
		
		$where = array();
		foreach ($rel as $key => $ref) {
			$where["$key="] = $foreign->$ref;
		}
		
		return $this->find($where, $order, $limit, $offset);
	}
915764
public function insertChild ($relationIdentifier, $id, $row, $foreignKey = null)
		{
			$relation = $this->getRelation($relationIdentifier);

			if (! $relation) {
				throw new RelationException('Invalid relation `' . $relationIdentifier);
			}

			if ($relation instanceof OneToMany || $relation instanceof OneToOne) {
				if (is_null($foreignKey)) {
					$foreignKey = $this->getPrimaryKey();
				}

				$row[$foreignKey] = $id;

				$this->database->createQuery()
					->insert()
					->into($relation->getRelatedTable())
					->set($row)
					->execute();

				return $this->database->insertId();

			} else if ($relation instanceof ManyToMany) {
				if (is_null($foreignKey)) {
					$foreignKey = $this->getPrimaryKey();
				}

				$childId = $this->database->createQuery()
					->insert()
					->into($relation->getRelatedTable())
					->set($row)
					->execute();

				$data = array(
					$foreignKey => $id,
					$this->database->primaryKey($relation->getRelatedTable()) => $childId,
				);

				$this->database->createQuery()
					->insert()
					->into($relation->getRelationalTable())
					->set($data)
					->execute();

				return $childId;

			} else {
				throw new RelationException('Invalid relation type `' . gettype($relation) . '`');
			}
		}
138503
public function getForeignKeyDDL(ForeignKey $fk)
    {
        if ($fk->isSkipSql()) {
            return;
        }
        $pattern = "CONSTRAINT %s
    FOREIGN KEY (%s)
    REFERENCES %s (%s)";
        $script = sprintf($pattern,
            $this->quoteIdentifier($fk->getName()),
            $this->getColumnListDDL($fk->getLocalColumns()),
            $this->quoteIdentifier($fk->getForeignTableName()),
            $this->getColumnListDDL($fk->getForeignColumns())
        );
        if ($fk->hasOnUpdate()) {
            $script .= "
    ON UPDATE " . $fk->getOnUpdate();
        }
        if ($fk->hasOnDelete()) {
            $script .= "
    ON DELETE " . $fk->getOnDelete();
        }

        return $script;
    }
308838
public function GetForRole($RoleID = '', $Offset = '0', $Limit = '50') {
      if (!is_array($RoleID))
         $RoleID = array($RoleID);
      
      $Offset = is_numeric($Offset) ? $Offset : 0;
      if ($Offset < 0)
         $Offset = 0;

      $Limit = is_numeric($Limit) ? $Limit : 0;
      if ($Limit < 0)
         $Limit = 0;
      
      $this->ActivityQuery();
      $Result = $this->SQL
         ->Join('UserRole ur', 'a.ActivityUserID = ur.UserID')
         ->WhereIn('ur.RoleID', $RoleID)
         ->Where('t.Public', '1')
         ->OrderBy('a.DateInserted', 'desc')
         ->Limit($Limit, $Offset)
         ->Get();
         
      $this->EventArguments['Data'] =& $Result;
      $this->FireEvent('AfterGet');
      
      return $Result;
   }
790304
protected function fetch($limit = null, $offset = null)
    {
        if (is_int($limit)) {
            $this->statement->limit($limit, $offset);
        }

        $statement = $this->statement->execute();

        if ($this->model instanceof Models) {
            $statement->setFetchMode(\PDO::FETCH_INTO, $this->model);
        } else {
            $statement->setFetchMode(\PDO::FETCH_CLASS|\PDO::FETCH_PROPS_LATE, $this->model);
        }

        return $statement;
    }
860443
static function customerList( $offset, $limit )
    {
        $db = eZDB::instance();

        $db_params = array();
        $db_params["offset"] =(int) $offset;
        $db_params["limit"] =(int) $limit;

        $customEmailResult = $db->arrayQuery( "SELECT DISTINCT email FROM ezorder WHERE is_temporary='0' ORDER BY email", $db_params );
        $customEmailArray = array();

        foreach( $customEmailResult as $customEmailRow )
        {
            $customEmail = $customEmailRow['email'];
            $customEmailArray[] = "'" . $customEmail . "'";
        }

        $emailString = implode( ", ", $customEmailArray );
        if ( !strlen( $emailString ) )
        {
            $emailString = "''";
        }

        $productItemArray = $db->arrayQuery(  "SELECT ezorder.id as order_id, user_id, email, ignore_vat, currency_code, ezproductcollection_item.*
                                                 FROM ezorder, ezproductcollection_item, ezproductcollection
                                                WHERE ezproductcollection_item.productcollection_id=ezorder.productcollection_id
                                                  AND is_temporary='0'
                                                  AND ezproductcollection_item.productcollection_id=ezproductcollection.id
                                                  AND email in ( $emailString )
                                             ORDER BY user_id, email, order_id" );


        $siteIni = eZINI::instance();
        $anonymousUserID = $siteIni->variable( 'UserSettings', 'AnonymousUserID' );

        $currentUserID = 0;
        $currentOrderID = 0;
        $currentUserEmail = "";
        $customArray = array();
        $accountName = null;
        $itemCount = 0;
        $hash = 0;
        $currencyCode = '';
        $ordersInfo = array();

        foreach( $productItemArray as $productItem )
        {
            $itemCount++;
            $currencyCode = $productItem['currency_code'];
            if ( $currencyCode == '' )
            {
                $currencyCode = eZOrder::fetchLocaleCurrencyCode();
            }

            $userID = $productItem['user_id'];
            $orderID = $productItem['order_id'];
            $order = eZOrder::fetch( $orderID );

            if ( $currentUserID != $userID && $itemCount != 1 )
            {
                $customArray[] = array( 'account_name' => $accountName,
                                        'orders_info' => $ordersInfo,
                                        'user_id' => $currentUserID,
                                        'email' => urlencode( $currentUserEmail ) );

                $ordersInfo = array();
                $accountName = $order->attribute( 'account_name' );
                $accountEmail = $order->attribute( 'account_email' );
            }

            $currentUserID = $userID;

            // If the custom is anoymous user
            if ( $currentUserID == $anonymousUserID )
            {
                $accountEmail = $order->attribute( 'email' );
                if ( $currentUserEmail == "" )
                {
                    $accountName = $order->attribute( 'account_name' );
                    $currentUserEmail = $accountEmail;
                }

                if ( $currentUserEmail != $accountEmail )
                {
                    $customArray[] = array( 'account_name' => $accountName,
                                            'orders_info' => $ordersInfo,
                                            'user_id' => $currentUserID,
                                            'email' => urlencode( $currentUserEmail ) );

                    $ordersInfo = array();
                    $accountName = $order->attribute( 'account_name' );
                    $accountEmail = $order->attribute( 'account_email' );
                    $currentUserEmail = $accountEmail;
                }
                $currentUserEmail = $accountEmail;
            }
            else
            {
                $currentUserEmail = 0;
            }

            $accountName = $order->attribute( 'account_name' );

            if ( !isset( $ordersInfo[$currencyCode] ) )
            {
                $ordersInfo[$currencyCode] = array( 'order_count' => 0,
                                                    'sum_ex_vat' => 0,
                                                    'sum_inc_vat' => 0 );
            }

            if (  $currentOrderID != $orderID )
            {
                $ordersInfo[$currencyCode]['order_count']++;
            }
            $currentOrderID = $orderID;

            if ( $productItem['ignore_vat'] == true )
            {
                $vatValue = 0;
            }
            else
            {
                $vatValue = $productItem['vat_value'];
            }

            $price = $productItem['price'];

            if ( $productItem['is_vat_inc'] )
            {
                $priceExVAT = $price / ( 100 + $vatValue ) * 100;
                $priceIncVAT = $price;
            }
            else
            {
                $priceExVAT = $price;
                $priceIncVAT = $price * ( 100 + $vatValue ) / 100;
            }

            $count = $productItem['item_count'];
            $realPricePercent = ( 100 - $productItem['discount'] ) / 100;
            $ordersInfo[$currencyCode]['sum_ex_vat'] += round( $count * $priceExVAT * $realPricePercent, 2 );
            $ordersInfo[$currencyCode]['sum_inc_vat'] += round( $count * $priceIncVAT * $realPricePercent, 2 );
        }
        if ( count( $productItemArray ) != 0 )
            $customArray[] = array( 'account_name' => $accountName,
                                    'orders_info' => $ordersInfo,
                                    'user_id' => $currentUserID,
                                    'email' => urlencode( $currentUserEmail ) );
        return $customArray;
    }
597615
protected function getForeignKeySqlDefinition(ForeignKey $foreignKey)
    {
        $def = '';
        if ($foreignKey->getConstraint()) {
            $def .= ' CONSTRAINT ' . $this->quoteColumnName($foreignKey->getConstraint());
        } else {
            $columnNames = [];
            foreach ($foreignKey->getColumns() as $column) {
                $columnNames[] = $this->quoteColumnName($column);
            }
            $def .= ' FOREIGN KEY (' . implode(',', $columnNames) . ')';
            $refColumnNames = [];
            foreach ($foreignKey->getReferencedColumns() as $column) {
                $refColumnNames[] = $this->quoteColumnName($column);
            }
            $def .= ' REFERENCES ' . $this->quoteTableName($foreignKey->getReferencedTable()->getName()) . ' (' . implode(',', $refColumnNames) . ')';
            if ($foreignKey->getOnDelete()) {
                $def .= ' ON DELETE ' . $foreignKey->getOnDelete();
            }
            if ($foreignKey->getOnUpdate()) {
                $def .= ' ON UPDATE ' . $foreignKey->getOnUpdate();
            }
        }

        return $def;
    }
681041
public function clientListDb($offset = null, $limit = null)
  {
    return $this->execute("clientdblist -count", array("start" => $offset, "duration" => $limit))->toAssocArray("cldbid");
  }
418930
public function findBy(array $criteria = [], array $orders = [], $limit = null, $offset = null): array
    {
        $queryCriteria = Criteria::create();

        foreach ($criteria as $prop => $value) {
            $queryCriteria->andWhere(Criteria::expr()->eq($prop, $value));
        }

        $queryCriteria->orderBy($orders);

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

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

        return $this->matching($queryCriteria);
    }
1215004
protected function getForeignKey($foreign)
    {
        $on = $this->wrapTable($foreign->on);

        // We need to columnize the columns that the foreign key is being defined for
        // so that it is a properly formatted list. Once we have done this, we can
        // return the foreign key SQL declaration to the calling method for use.
        $columns = $this->columnize($foreign->columns);

        $onColumns = $this->columnize((array) $foreign->references);

        return ", foreign key($columns) references $on($onColumns)";
    }
144796
function limit( $count, $offset = null ) {

        if ( $this->parent_ ) {

            throw new \LogicException( 'Cannot limit referenced result' );

        }

        $clone = clone $this;

        $clone->limitCount = $count;
        $clone->limitOffset = $offset;

        return $clone;

    }
614976
public function addChildObject($alias, $parent_id, $model, $foreignKey) {
        $query = array(
            'alias' => $alias,
            'parent_id' => $parent_id,
            'model' => $model,
            'foreign_key' => $foreignKey
        );

        $result = $this->find('first', array(
            'conditions' => $query
        ));

        if ($result) {
            return $result;
        }

        $this->create();

        if ($this->save($query)) {
            $this->deleteCache(array('RequestObject::hasAlias', $alias));

            return $this->getByAlias($alias);
        }

        return null;
    }
1092409
public function complexFindBy(array $criteria, array $orderBy = [], $limit = null, $offset = null)
    {
        $qb = $this->createQueryBuilder("p");

        foreach($criteria as $c => $v){
            $qb->andWhere("p.$c $v");
        }
        foreach($orderBy as $c => $v){
            $qb->addOrderBy("p.".$c,$v);
        }
        if (isset($limit)) $qb->setMaxResults($limit);
        if (isset($offset)) $qb->setFirstResult($offset);

        return $qb->getQuery()->getResult();
    }
859739
public function findRelatedSourceRecords(int $sourceId, int $limit = null): array
    {
        /** @var Relations $relations */
        $relations = $this->framework->getAdapter(Relations::class);

        if (false === ($relation = $relations->getRelation($this->sourceTable, $this->sourceField))) {
            throw new \RuntimeException(\sprintf('The field %s.%s is not related', $this->sourceTable, $this->sourceField));
        }

        /** @var Model $relationsModel */
        $relationsModel = $this->framework->getAdapter(Model::class);

        $tagIds = $relationsModel->getRelatedValues($this->sourceTable, $this->sourceField, $sourceId);
        $tagIds = \array_values(\array_unique($tagIds));
        $tagIds = \array_map('intval', $tagIds);

        // Return if there are no tags
        if (0 === \count($tagIds)) {
            return [];
        }

        $query = \sprintf(
            'SELECT %s, COUNT(*) AS relevance FROM %s WHERE %s IN (%s) AND %s != ? GROUP BY %s ORDER BY relevance DESC',
            $relation['reference_field'],
            $relation['table'],
            $relation['related_field'],
            \implode(',', $tagIds),
            $relation['reference_field'],
            $relation['reference_field']
        );

        // Set the limit
        if ($limit > 0) {
            $query .= \sprintf(' LIMIT %s', $limit);
        }

        $related = [];

        // Generate the related records
        foreach ($this->db->fetchAll($query, [$sourceId]) as $record) {
            $related[$record[$relation['reference_field']]] = [
                'total' => \count($tagIds),
                'found' => $record['relevance'],
                'prcnt' => ($record['relevance'] / \count($tagIds)) * 100,
            ];
        }

        return $related;
    }
382896
protected function getManyToOneRelationSelectSQL(RelationDescription $relationDescription,
          array $otherObjectProxies, $otherRole, $criteria=null, $orderby=null,
          PagingInfo $pagingInfo=null) {
    $thisAttr = $this->getAttribute($relationDescription->getFkName());
    $tableName = $this->getRealTableName();

    // id parameters
    $parameters = [];
    $idPlaceholder = ':'.$tableName.'_'.$thisAttr->getName();
    for ($i=0, $count=sizeof($otherObjectProxies); $i<$count; $i++) {
      $dbid = $otherObjectProxies[$i]->getValue($relationDescription->getIdName());
      if ($dbid === null) {
        $dbid = SQLConst::NULL();
      }
      $parameters[$idPlaceholder.$i] = $dbid;
    }

    // statement
    $selectStmt = $this->getRelationStatement($thisAttr, $parameters,
          $otherObjectProxies, $otherRole, $criteria, $orderby, $pagingInfo);
    return [$selectStmt, $relationDescription->getIdName(), $relationDescription->getFkName()];
  }
658828
static public function fetchByParentID( $parentID, $offset = 0, $limit = null, $mainTranslation = false )
    {
        if ( $offset === 0 && $limit === null )
        {
            $limits = null;
        }
        else
        {
            $limits = array( 'offset' => $offset, 'limit' => $limit );
        }
        return self::fetchList(
            array( 'parent_id' => $parentID, 'main_tag_id' => 0 ),
            $limits,
            null,
            $mainTranslation
        );
    }
612023
public function getCompanies($offset = 0, $limit = 25)
    {
        list($offset, $limit) = $this->normalizeOffsetAndLimit($offset, $limit);

        return $this->request('companies', [
            'offset' => $offset,
            'limit' => $limit,
        ]);
    }