2017-12-08 32 views
1

私はbelongsToMany関係を使用しようとしていますが、問題は一度もありませんでしたが何らかの理由で空を返します。Laravel 5.5 BelongsToMany returns empty

私はこのような店舗モデルの私の関係を設定している:私は関係をテストするとき、それはありませんが、

public function images() 
    { 
     return $this->belongsToMany('App\Images', 'images_stores', 'image_id', 'store_id'); 
    } 

、それは何のエラーちょうど空のコレクションを返します。これは私がデータにアクセスする方法です:

public function edit($id) 
    { 
     $store = Store::find($id); 
     dd($store->images); 

     return view('admin.pages.store.edit', compact('store')); 
    } 

しかし、それはちょうど私が誰かがこれで私を助けることができる願って、空のコレクションを返します。これらは私のマイグレーションファイルですが、問題はマイグレーションファイル内にないと思います。

Schema::create('images', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->string('path'); 
     $table->timestamps(); 
    }); 
    // pivot table 
    Schema::create('images_stores', function (Blueprint $table) { 
     $table->increments('id'); 

     $table->integer('image_id')->unsigned()->nullable(); 
     $table->foreign('image_id')->references('id')->on('images')->onDelete('cascade'); 

     $table->integer('store_id')->unsigned()->nullable(); 
     $table->foreign('store_id')->references('id')->on('stores')->onDelete('cascade'); 

     $table->timestamps(); 
    }); 
    // store table 
    Schema::create('stores', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->string('location'); 
     $table->string('email'); 
     $table->timestamps(); 
    }); 

ありがとうございます。

答えて

5

idが逆転していると思います。これを試してみてください:

public function images() 
{ 
    return $this->belongsToMany('App\Images', 'images_stores', 'store_id', 'image_id'); 
} 
+0

私はそれを試してみましたが、それはエラーを返すでしょうが、それは非常にverryありがとう! – frogeyedman

+0

私はあなたを助けることができてうれしいです!あなたは正しい答えとして受け入れることができますか? – Laerte