-
-
Notifications
You must be signed in to change notification settings - Fork 7
Blueprint Macro: Foreign Key
Nasrul Hazim Bin Mohamad edited this page Jun 14, 2018
·
1 revision
Foreign Key(FK) is a common setup where you need a thing, belongs to something and adding FK require some setups.
But with addForeign
, that some setups, has been simplified.
User Cases
- You need to setup a post belongs to a user. Add the following in your
posts
migration file.
$table->addForeign('users');
This will add user_id
, in the posts
table and the relationship of the posts
table and users
table automatically.
Easy setup right?
- Probably you need custom FK name.
Above code are equivalent to previous implementation:
$table->addForeign('users', ['fk' => 'customer_id']);
- You want it to be nullable
$table->addForeign('users', ['nullable' => true]);
- You want FK as Big Integer (case where you tons of data)
$table->addForeign('users', ['bigInteger' => true]);
- And lastly, probably you reference id, is not the default
id
.
$table->addForeign('users', ['reference' => 'profile_id']);
Other FK Related Macros
$table->addForeign('users');
$table->addNullableForeign('users');
$table->referenceOn('user_id', 'users', 'id');
$table->belongsTo('user_id', 'users', 'id');
$table->nullableBelongsTo('user_id', 'users', 'id');
TIPS
$table->user(); // same as $table->addForeign('users');
$table->user(true); // same as $table->addForeign('users', ['nullable' => true]);