Skip to content

Commit

Permalink
Added Foreign Key section
Browse files Browse the repository at this point in the history
  • Loading branch information
arvidbjorkstrom committed Jan 30, 2013
1 parent cad0ffa commit be7d91e
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- [Dropping Columns](#dropping-columns)
- [Adding Indexes](#adding-indexes)
- [Dropping Indexes](#dropping-indexes)
- [Foreign Keys](#foreign-keys)

<a name="introduction"></a>
## Introduction
Expand Down Expand Up @@ -108,3 +109,38 @@ Command | Description
`$table->dropPrimary('users_id_primary');` | Dropping a primary key from the "users" table
`$table->dropUnique('users_email_unique');` | Dropping a unique index from the "users" table
`$table->dropIndex('geo_state_index');` | Dropping a basic index from the "geo" table

<a name="foreign-keys"></a>
## Adding Columns

When building your database you're very likely have columns in one table referencing primary keys of another table, for instance when you're using [Eloquent's Relationships](eloquent#relationships) features. If you let your database engine know this you can leverage it's capacity for keeping this data consistent and working smothly.

> **Note:** Both columns muse be of the same type. Primary keys are unsigned integers so referencing columns need to be `->unsigned()` aswell.
> **Note:** The referenced table must created before the referencing table.
**Add A Foreign Key Constraint**

$table->foreign("user_id")->references('id')->on('users');

You can also specify what you want the database engine to do when the referenced column is updated or deleted

$table->foreign("user_id")->references('id')->on('users')->onDelete('restrict');

$table->foreign("user_id")->references('id')->on('users')->onUpdate('cascade')->onDelete('restrict');

Option | Description
------------- | -------------
`restrict` | Prevents deletion or update of the referenced row
`cascade` | The action replicates - the column is updated to the new value, or the row is deleted along with the referenced row
`set null` | The value is set to null when the foreign key is updated or deleted
`no action` | Error is raised, but the action is performed
`set default` | The value is set to the default for the column when the foreign key is updated or deleted

> **Note:** The default option is `no action`
> **Note:** `set default` is not supported by MySQL InnoDB!
**Dropping Foreign Key Constraints**

$table->dropForeign("user_id");

0 comments on commit be7d91e

Please sign in to comment.