<?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');
}
}
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');
}
...
1 回答
您可以通过对模型执行此类操作(未经测试),将多个车辆和车辆的事件与多个事件相关联:
Vehicle.php
Event.php
您还需要数据透视表的迁移文件:
然后你可以使用attach()和detach()将车辆与事件相关联,反之亦然 .