Skip to content

Improving foreign key API #770

@markstory

Description

@markstory

Building foreign keys through the addForeignKey method requires remembering 4 positional arguments, and the ordering. While it is decent to use when writing migrations it is more reads with more difficulty.

        $this->table('constraint_users')
            ->addForeignKey(
                'role_id',
                'constraint_roles',
                'id',
                [
                    'update' => 'NO_ACTION',
                    'delete' => 'NO_ACTION',
                    'constraint' => 'role_id_0_fk'
                ]
            )
            ->update();

Is the current API. We've used up a really good method name with addForeignKey and the alternative names I could come up with clunky. What we could do with relative ease though is widen the type on the first parameter of addForeignKey to include a new builder object:

        $this->table('constraint_users')
            ->addForeignKey(
                $this->foreignKey('role_id')
                    ->references('constraint_roles', 'id')
                    // Could also be an enum
                    ->updateAction('NO_ACTION')
                    ->deleteAction('NO_ACTION')
                    ->name('role_id_0_fk')
            )
            ->update();

While this is more verbose, it is more clear about what is going on, and the API can be well-typed.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions