jeudi 30 juin 2016

Laravel 5.2 - Eloquent Many to Many Relationship

I have 2 models and 3 migrations, Models are

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

and Migrations are

1- for media table the schema is:

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

2- for gallery table the schema is:

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

3- a third joining table for media_gallery many to many relationship:

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

Concept: I have Dropzone installed and working so than I can upload items to the Gallery table, but what I want to do is that I make a Media item so that it holds one or more Gallery items, and a gallery item can be related to many media item

What I've tried: I made a form that holds each gallery item with a check box holds the id of the item, this is how I handle it in my 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);
}

Error shows up:

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)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire