/**
* Returns foreign keys in $fromRecord with source column names as key
* and foreign column names in the corresponding $matchesRecord as value.
* The method returns the first matching foreign key between these 2 records.
* @param TActiveRecord $fromRecord
* @param TActiveRecord $matchesRecord
* @return array foreign keys with source column names as key and foreign column names as value.
*/
protected function findForeignKeys($from, $matchesRecord, $loose = false)
{
$gateway = $matchesRecord->getRecordGateway();
$recordTableInfo = $gateway->getRecordTableInfo($matchesRecord);
$matchingTableName = strtolower($recordTableInfo->getTableName());
$matchingFullTableName = strtolower($recordTableInfo->getTableFullName());
$tableInfo = $from;
if ($from instanceof TActiveRecord) {
$tableInfo = $gateway->getRecordTableInfo($from);
}
//find first non-empty FK
foreach ($tableInfo->getForeignKeys() as $fkeys) {
$fkTable = strtolower($fkeys['table']);
if ($fkTable === $matchingTableName || $fkTable === $matchingFullTableName) {
$hasFkField = !$loose && $this->getContext()->hasFkField();
$key = $hasFkField ? $this->getFkFields($fkeys['keys']) : $fkeys['keys'];
if (!empty($key)) {
return $key;
}
}
}
//none found
$matching = $gateway->getRecordTableInfo($matchesRecord)->getTableFullName();
throw new TActiveRecordException('ar_relations_missing_fk', $tableInfo->getTableFullName(), $matching);
}