Laravel 5.2 - Eloquent 多对多关系

Laravel 5.2 - Eloquent Many to Many Relationship

我有 2 个模型和 3 个迁移,模型是

1-Media:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Media extends Model
{
  public function gallery(){
        return $this->hasMany('App\Gallery', 'media_gallery');
    }
}

2-Gallery:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Gallery extends Model
{
  public function media(){
        return $this->belongsToMany('App\Media', 'media_gallery');
    }
}

迁移是

1- 对于 media table 架构是:

Schema::create('media', function (Blueprint $table) {
   $table->increments('id');
   $table->timestamps();
});

2- 对于 gallery table 架构是:

Schema::create('galleries', function (Blueprint $table) {
   $table->increments('id');
   $table->timestamps();
   $table->string('path');
   $table->string('type');
});

3- 第三个加入 table 用于 media_gallery 多对多 关系:

Schema::create('media_gallery', function (Blueprint $table) {
    $table->increments('id');
    $table->timestamps();
    $table->integer('media_id');
    $table->integer('gallery_id');
});

概念: 我安装了 Dropzone 并正常工作,因此我可以将项目上传到 Gallery table,但我想做的是我制作了一个 Media 项目,这样它可以容纳一个或多个 Gallery 项目,并且一个 gallery 项目可以与许多 media 项目相关

什么 我试过: 我制作了一个包含每个图库项目的表单,其中一个复选框包含项目的 id,这就是我在控制器中处理它的方式...

public function MediaPostUpload(Request $request){

        $media = new Media();
        $media->save();

        //fetching ids of checked boxes
        $galleryItems = $request['galleryItems'];
        $ids = array();
        if(!empty($galleryItems)){
            foreach($galleryItems as $itemId){
                $ids[] = $itemId;
            }
        }
        $media->gallery()->attach($ids);
}

出现错误

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'galleries.media_gallery' in 'where clause' (SQL: select * from galleries where galleries.media_gallery = 1 and galleries.media_gallery is not null)

您也必须在媒体模型中使用 belongsToMany 关联:

class Media extends Model
{
  public function gallery(){
        return $this->belongsToMany('App\Gallery', 'media_gallery');
    }
}

多对多没有反向关系,它是相同的关系,因为主元总是有两个键。