I’ve been having to look up relationship schemas too frequently and haven’t found a decent place that outlines them with migration and eloquent relationship declaration side by side. So if you’re looking for how to build a migration for (insert here) relationship, here it is.
*Based on Laravel 7
One to One
// Model A Migration
public function up()
{
Schema::table('A', function (Blueprint $table) {
$table->unsignedBigInteger('id');
});
}
// Model B Migration
public function up()
{
Schema::table('B', function (Blueprint $table) {
$table->unsignedBigInteger('id');
$table->unsignedBigInteger('A_id');
$table->foreign('A_id')->references('id')->on('A');
});
}
// A Model
public function b(){
$this->hasOne(B::class);
}
// B Model
public function a(){
$this->belongsTo(A::class);
}
One to Many
The migration looks the same as One to One, and similar in the Eloquent model. Just change ‘hasOne’ in the A class to ‘hasMany’
// Model A Migration
public function up()
{
Schema::table('A', function (Blueprint $table) {
$table->unsignedBigInteger('id');
});
}
// Model B Migration
public function up()
{
Schema::table('B', function (Blueprint $table) {
$table->unsignedBigInteger('id');
$table->unsignedBigInteger('A_id');
$table->foreign('A_id')->references('id')->on('A');
});
}
// A Model
public function b(){
$this->hasMany(B::class);
}
// B Model
public function a(){
$this->belongsTo(A::class);
}
Many to Many
Many to many relationships requires a third table called a pivot table that links the two.
// Model A Migration
public function up()
{
Schema::table('Amodel', function (Blueprint $table) {
$table->unsignedBigInteger('id');
});
}
// Model B Migration
public function up()
{
Schema::table('Bmodel', function (Blueprint $table) {
$table->unsignedBigInteger('id');
});
}
// Pivot Table migration named A_B_table
// naming structure is important in Laravel, the model names are singular
// and in alphabetical order
public function up()
{
Schema::table('A_B', function (Blueprint $table) {
$table->unsignedBigInteger('A_id');
$table->foreign('A_id')->references('id')->on('A');
$table->unsignedBigInteger('B_id');
$table->foreign('B_id')->references('id')->on('B');
});
}
// A Model
public function b(){
$this->belongsToMany(B::class);
}
// B Model
public function a(){
$this->belongsToMany(A::class);
}
Conclusion
Name | Migration | Eloquent Relationship |
One to One A | id – integer | hasOne – b |
One to One B | id – integer a_id – integer | belongsTo – a |
One to Many A | id – integer | hasMany – b |
One to Many B | id – integer a_id – integer | belongsTo – a |
Many to Many A | id – integer | belongsToMany – b |
Many to Many B | id – integer | belongsToMany – a |
Many to Many Pivot | a_id – integer b_id – integer |