Skip to content

Foreign keys

Foreign keys are used to create a relationship between two tables.

The Schema class allows you to define foreign keys using the foreign_key() method. This method creates a new Foreign_Key object and adds it to the $foreign_keys array in the Schema class.

Defining foreign keys

You can define a foreign key on a column by calling the foreign_key() method on the Schema object.

php
$schema = new Schema( 'my_table', function ( Schema $table ) {
	$table->foreign_key( 'user_id' )
		->reference( 'users', 'id' )
		->on_delete( 'CASCADE' )
		->on_update( 'CASCADE' );
});

Fluent interface

The Foreign_Key class uses a fluent interface, allowing method chaining for easy configuration.

You can customize various aspects of the foreign key:

  • Set the reference table and column using reference()
  • Set just the reference table using reference_table()
  • Set just the reference column using reference_column()
  • Set the ON DELETE action using on_delete()
  • Set the ON UPDATE action using on_update()

The reference() method is a key part of defining a foreign key relationship. This method sets both the referenced table and the referenced column in a single call. It's a convenient way to specify the "target" of the foreign key relationship.

Parameters

  • $reference_table: The name of the table that this foreign key is referencing.
  • $reference_column: The name of the column in the referenced table that this foreign key is pointing to.

Default values

If not specified, the ON DELETE and ON UPDATE actions default to 'NO ACTION'.