【问题标题】:Laravel Many-to-Many Pivot TableLaravel 多对多数据透视表
【发布时间】:2017-04-11 12:17:04
【问题描述】:

我有一个关于在 laravel 中使用数据透视表的相当简单的问题。首先我会提供一些关于我的情况的信息,我有两个表名为“Vehicles”和“Events”。现在我想创建一个表格,用于存放已注册参加活动的车辆。现在这两个表之间的关系将是“许多车辆可以注册许多事件”,反之亦然。数据透视表是否是实现此目的的最佳方式,如果是这样,同一表中是否可以有更多奇异值?

【问题讨论】:

    标签: laravel many-to-many pivot-table


    【解决方案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() 将车辆与事件相关联,反之亦然。

    【讨论】:

    • 是否可以将数据透视表与另一个表结合起来,例如我有一个包含更多一般信息的表,我也想在里面放上外国人?
    • 您可以使用$this-&gt;hasMany(Vehicle::class)-&gt;withPivot('column1', 'column2'); 之类的方式将其他字段添加到数据透视表中,可以使用$model-&gt;pivot-&gt;column1 进行访问
    • 谢谢,这正是我想知道的
    猜你喜欢
    • 2019-02-27
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2014-12-13
    • 2019-03-25
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多