/** * @param string $entityClass * @param string $key * @param null $column * @return StoredEntity|null * @throws NoReferenceException */ public function reference($entityClass, $key = null, $column = null) { if ($this->cachedReferences == null) { $this->cachedReferences = new ArrayHash(); } if ($this->isNewEntity()) { return null; } if ($key == null) { $columnToDiscoverReference = $entityClass; $reflectProperty = $this->getPropertyByColumnName($columnToDiscoverReference); if ($reflectProperty) { $entityClass = $this->getReferenceClassForProperty($reflectProperty); if (!$entityClass) { throw new NoReferenceException($columnToDiscoverReference); } $column = $columnToDiscoverReference; $key = $entityClass::getTableName($this->annotationReader); } } self::mustBeChildOf($entityClass, StoredEntity::class); if (!$this->cachedReferences->offsetExists($key)) { $reference = $entityClass::create($this, $this->row->getTable()->getReferencedTable($this->row, $key, $column)); $this->cachedReferences->offsetSet($key, $reference); } return $this->cachedReferences->offsetGet($key); }
/** * Returns referenced row. * @param ActiveRow * @param string * @param string|NULL * @return ActiveRow|NULL|FALSE NULL if the row does not exist, FALSE if the relationship does not exist */ public function getReferencedTable(ActiveRow $row, $table, $column = NULL) { if (!$column) { $belongsTo = $this->conventions->getBelongsToReference($this->name, $table); if (!$belongsTo) { return FALSE; } list($table, $column) = $belongsTo; } if (!$row->accessColumn($column)) { return FALSE; } $checkPrimaryKey = $row[$column]; $referenced =& $this->refCache['referenced'][$this->getSpecificCacheKey()]["{$table}.{$column}"]; $selection =& $referenced['selection']; $cacheKeys =& $referenced['cacheKeys']; if ($selection === NULL || $checkPrimaryKey !== NULL && !isset($cacheKeys[$checkPrimaryKey])) { $this->execute(); $cacheKeys = []; foreach ($this->rows as $row) { if ($row[$column] === NULL) { continue; } $key = $row[$column]; $cacheKeys[$key] = TRUE; } if ($cacheKeys) { $selection = $this->createSelectionInstance($table); //search for foreign key column name which is referenced from activeRow parent table to table from which is selection made $foreign = $this->conventions->getForeign($row->getTable()->getName(), $column); $primary = $foreign == NULL ? $selection->getPrimary() : $foreign; $selection->where($primary, array_keys($cacheKeys)); } else { $selection = NULL; } } return $selection; //return isset($selection[$checkPrimaryKey]) ? $selection[$checkPrimaryKey] : NULL; }