Created
October 4, 2018 16:55
-
-
Save pmkay/5bd74b4c4e540414c8d64efcfc9a8f18 to your computer and use it in GitHub Desktop.
Creating a Pivot Table in Laravel Example
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 | |
public function up() | |
{ | |
Schema::create('post_tag', function (Blueprint $table) { | |
$table->primary(['post_id', 'tag_id']); | |
$table->unsignedInteger('post_id'); | |
$table->unsignedInteger('tag_id'); | |
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade'); | |
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade'); | |
$table->timestamps(); | |
} | |
} |
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
class Post | |
{ | |
public function tags() | |
{ | |
return $this->belongsToMany(Tag::class)->withTimestamps; | |
} | |
} |
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
Class Tag | |
{ | |
public function posts() | |
{ | |
return $this->belongsToMany(Post::class); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment