2016-11-27 153 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

相关问题