Browse Source

Lesson 30: tags and relation ('pivot') tables.

Frederic G. MARAND 6 years ago
parent
commit
8770459b46
3 changed files with 59 additions and 0 deletions
  1. 5 0
      app/Post.php
  2. 15 0
      app/Tag.php
  3. 39 0
      database/migrations/2017_09_09_152726_create_tags_table.php

+ 5 - 0
app/Post.php

@@ -75,4 +75,9 @@ EOT
 
         return $query;
     }
+
+    public function tags()
+    {
+        return $this->belongsToMany(Tag::class);
+    }
 }

+ 15 - 0
app/Tag.php

@@ -0,0 +1,15 @@
+<?php
+
+namespace App;
+
+use Illuminate\Database\Eloquent\Model;
+
+class Tag extends Model
+{
+    protected $fillable = ['name'];
+
+    public function posts()
+    {
+        return $this->belongsToMany(Post::class);
+    }
+}

+ 39 - 0
database/migrations/2017_09_09_152726_create_tags_table.php

@@ -0,0 +1,39 @@
+<?php
+
+use Illuminate\Support\Facades\Schema;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Database\Migrations\Migration;
+
+class CreateTagsTable extends Migration
+{
+    /**
+     * Run the migrations.
+     *
+     * @return void
+     */
+    public function up()
+    {
+        Schema::create('tags', function (Blueprint $table) {
+            $table->increments('id');
+            $table->string('name')->unique();
+            $table->timestamps();
+        });
+
+        Schema::create('post_tag', function (Blueprint $table) {
+            $table->integer('post_id');
+            $table->integer('tag_id');
+            $table->primary(['post_id', 'tag_id']);
+        });
+    }
+
+    /**
+     * Reverse the migrations.
+     *
+     * @return void
+     */
+    public function down()
+    {
+        Schema::dropIfExists('post_tag');
+        Schema::dropIfExists('tags');
+    }
+}