首页 文章

Laravel多对多数据透视表

提问于
浏览
0

关于在laravel中使用Pivot表,我有一个相当简单的问题 . 首先,我提供一些有关我的情况的信息,我有两个表名为“车辆”和“事件” . 现在我想创建一个用于存放已注册事件的车辆的表 . 现在,这两个表之间的关系是“许多车辆可以注册多个事件”,反之亦然 . 将Pivot表作为实现此目的的最佳方法,如果可以的话,可以在同一个表中使用更多的奇异值吗?

1 回答

  • 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');
        }
    }
    

    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()将车辆与事件相关联,反之亦然 .

相关问题