我有 2 个模型和 3 个迁移,模型是
1-媒体
:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Media extends Model
{
public function gallery(){
return $this->hasMany('App\Gallery', 'media_gallery');
}
}
2-画廊
:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Gallery extends Model
{
public function media(){
return $this->belongsToMany('App\Media', 'media_gallery');
}
}
和迁移是
1- 对于 media
表,架构是:
Schema::create('media', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
});
2- gallery
表的模式是:
Schema::create('galleries', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('path');
$table->string('type');
});
3- media_gallery
多对多关系的第三个连接表:
Schema::create('media_gallery', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('media_id');
$table->integer('gallery_id');
});
概念: 我安装了 Dropzone 并正常工作,因此我可以将项目上传到 Gallery
表,但我想做的是制作一个 Media
项目,以便它包含一个或多个 Gallery
项目,而一个 gallery
项目可以与多个 media
项目
什么我试过:
我制作了一个包含每个图库项目的表单,其中一个复选框包含项目的 id
,这就是我在 Controller 中处理它的方式......
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
wheregalleries
.media_gallery
= 1 andgalleries
.media_gallery
is not null)
最佳答案
你也必须在你的媒体模型中使用 belongsToMany 关联:
class Media extends Model
{
public function gallery(){
return $this->belongsToMany('App\Gallery', 'media_gallery');
}
}
多对多没有反向关系,它是相同的关系,因为枢轴总是有两个键。
关于database - Laravel 5.2 - Eloquent 多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38130803/