在實際開發中多對多的開發還是比較常見的
1.1首先由migrate來創建表(文章表)

1.2同理創建標簽表

1.3這是 我會的到如下結果:

2.1在數據遷移表contents中添加幾個字段
public function up() { Schema::create('contents', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); }); }
2.2在數據遷移表tag中添加如下字段:
public function up() { Schema::create('tags', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->timestamps(); }); Schema::create('content_tag', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('content_id')->unsigned()->index(); $table->integer('tag_id')->unsigned()->index(); //設置外鍵 $table->foreign('content_id')->references('id')->on('contents')->onDelete('cascade'); $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade'); $table->timestamps(); }); }
3.3這時運行如下的artisan命令
php artisan migrate
在數據庫表中可以看到如下表

這時就在兩個模型中各添加一個方法
//在Content模型中 添加 public function tags() { return $this->belongsToMany(Tag::class); } //在Tag模型中 添加 public function contents() { return $this->belongsToMany(Content::class); }
現在進入測試階段代碼如下
//向各表中添加20條數據 factory(Content::class,20)->create(); factory(Tag::class,20)->create();
結果如下:

最后幾步配置路由如下
Route::get('/', function () {
$content = \App\Content::find(3);
//在content_tag表中添加tag標簽為3和content表中id為3的數據
$content_tag = $content->tags()->attach(3);
//進行刪除數據
// $content_tag = $content->tags()->detach(3);
dd($content_tag);
return view('welcome');
});
緊接着啟動服務器
php artisan serve
測試結果:在表中的數據

刪除之后的結果

