2016-11-27 274 views
0

我有一個關於在laravel中使用數據透視表的相當簡單的問題。首先生病給我一些關於我的情況的信息,我有兩個表格「車輛」和「事件」。現在我想創建一張桌子,用來放置已註冊事件的車輛。現在這兩張表之間的關係是「許多車輛可以註冊許多事件」,反之亦然。一個數據透視表是否是實現這一目標的最佳方式,如果可以的話,更多的奇異值可以放在同一個表中嗎?Laravel多對多數據透視表

回答

1

可以多輛事件,並通過做這樣的事情與你的模型(未測試)車輛到多個事件相關聯:

Vehicle.php

<?php 

namespace App; 

use App\Event; 
use Illuminate\Database\Eloquent\Model; 

class Vehicle extends Model 
{ 

    ... 


    /** 
    * Get the events that this vehicle belongs to. 
    * 
    * @return \App\Event 
    */ 
    public function events() 
    { 
     return $this->belongsToMany(Event::class, 'vehicle_event'); 
    } 
} 

事件。 php

<?php 

namespace App; 

use App\Vehicle; 
use Illuminate\Database\Eloquent\Model; 

class Event extends Model 
{ 

    ... 


    /** 
    * Get the vehicles that this event has. 
    * 
    * @return \App\Vehicle 
    */ 
    public function events() 
    { 
     return $this->hasMany(Vehicle::class, 'vehicle_event'); 
    } 
} 

您還需要一個遷移文件數據透視表:

... 

    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('vehicle_event', function(Blueprint $table) 
     { 
      $table->integer('vehicle_id')->unsigned()->index(); 
      $table->foreign('vehicle_id')->references('id')->on('vehicles'); 
      $table->integer('event_id')->unsigned()->index(); 
      $table->foreign('event_id')->references('id')->on('events'); 
     }); 
    } 

    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::dropIfExists('vehicle_event'); 
    } 

    ... 

然後你可以使用attach()detach()車輛的事件,反之亦然關聯。

+0

是否可以將數據透視表與其他表結合使用,例如,我有一張更具一般性信息的表格,並且我還想讓外國人也參與其中? – JoshuaJohnson2896

+0

您可以使用'$ this-> hasMany(Vehicle :: class) - > withPivot('column1','column2');''可以通過$ model->訪問其他字段到數據透視表中, pivot-> column1' – Winter

+0

謝謝,那正是我想知道的 – JoshuaJohnson2896

相關問題