Last active
June 20, 2019 19:42
-
-
Save tjventurini/707ee330f6bfb7db08c3d34d73db5b1d to your computer and use it in GitHub Desktop.
Laravel Migration for Pivot Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Illuminate\Support\Facades\Schema; | |
use Illuminate\Database\Schema\Blueprint; | |
use Illuminate\Database\Migrations\Migration; | |
class CreatePostTagPivotTable extends Migration | |
{ | |
/** | |
* Run the migrations. | |
* | |
* @return void | |
*/ | |
public function up() | |
{ | |
DB::transaction(function () { | |
Schema::create('post_tag', function (Blueprint $table) { | |
// create post_id column | |
// ! make sure to use the same column type | |
// as in the referenced column | |
// e.g. integer or bigInteger | |
$table->bigInteger('post_id') | |
->unsigned() | |
->nullable(); | |
// make post_id column a foreign key | |
$table->foreign('post_id') | |
->references('id') | |
->on('posts') | |
->onDelete('cascade'); | |
// create tag_id column | |
// ! make sure to use the same column type | |
// as in the referenced column | |
// e.g. integer or bigInteger | |
$table->bigInteger('tag_id') | |
->unsigned() | |
->nullable(); | |
// make tag_id column a foreign key | |
$table->foreign('tag_id') | |
->references('id') | |
->on('tags') | |
->onDelete('cascade'); | |
}); | |
}); | |
} | |
/** | |
* Reverse the migrations. | |
* | |
* @return void | |
*/ | |
public function down() | |
{ | |
Schema::dropIfExists('post_tag'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment