0 follower

Final Class Yiisoft\Db\Migration\Service\Generate\ForeignKeyFactory

InheritanceYiisoft\Db\Migration\Service\Generate\ForeignKeyFactory

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( \Yiisoft\Db\Connection\ConnectionInterface $db, \Symfony\Component\Console\Style\SymfonyStyle|null $io, boolean $useTablePrefix )
$db \Yiisoft\Db\Connection\ConnectionInterface
$io \Symfony\Component\Console\Style\SymfonyStyle|null
$useTablePrefix boolean

                public function __construct(
    private readonly ConnectionInterface $db,
    private readonly ?SymfonyStyle $io,
    private readonly bool $useTablePrefix,
) {}

            
create() public method

public Yiisoft\Db\Migration\Service\Generate\ForeignKey create ( string $table, string $column, string $relatedTable, string|null $relatedColumn )
$table string
$column string
$relatedTable string
$relatedColumn string|null

                public function create(
    string $table,
    string $column,
    string $relatedTable,
    ?string $relatedColumn,
): ForeignKey {
    /**
     * We're trying to get it from the table schema.
     *
     * {@see https://github.com/yiisoft/yii2/issues/12748}
     */
    if ($relatedColumn === null) {
        $relatedColumn = 'id';
        $tablePrimaryKeys = $this->db->getSchema()->getTablePrimaryKey($relatedTable);
        if ($tablePrimaryKeys !== null) {
            $primaryKeys = $tablePrimaryKeys->columnNames;
            match (count($primaryKeys)) {
                1 => $relatedColumn = $primaryKeys[0],
                default => $this->io?->writeln(
                    "<fg=yellow> Related table for field \"$column\" exists, but primary key is composite. Default name \"id\" will be used for related field</>\n",
                ),
            };
        } else {
            $this->io?->writeln(
                "<fg=yellow> Related table for field \"$column\" exists, but does not have a primary key. Default name \"id\" will be used for related field.</>\n",
            );
        }
    }
    return new ForeignKey(
        "idx-$table-$column",
        "fk-$table-$column",
        $column,
        $this->useTablePrefix ? '{{%' . $relatedTable . '}}' : $relatedTable,
        $relatedColumn,
    );
}