2017-08-09 14 views
0

私は2つのテーブルを持っており、私は外部キーでデータに応答したいと思っています。Laravel 5.4 - 外部キーによるJSONデータへの応答方法

TableCategory

public function up() 
    { 
     Schema::create('categories', function (Blueprint $table) { 
      $table->increments('id',10); 
      $table->string('name',100)->nullable(); 
      $table->timestamps(); 
     }); 
    } 

TableSong

public function up() 
    { 
     Schema::create('songs', function (Blueprint $table) { 
      $table->increments('id',10); 
      $table->string('name',100)->nullalbe(); 
      $table->string('url',500)->nullalbe(); 
      $table->integer('categories_id')->unsigned(); 
      $table->timestamps(); 

      $table->foreign('categories_id')->references('id')->on('categories'); 

     }); 
    } 

CategoryModel

class CategoryModel extends Model 
{ 
    protected $table = 'categories'; 
    protected $fillable = [ 
     'id', 
     'name', 
    ]; 
    public function song() 
    { 
     return $this->hasMany(SongModel::class); 
    } 
} 

SongModel

class SongModel extends Model 
{ 
    protected $table = 'songs'; 
    protected $fillable = [ 
     'id', 
     'name', 
     'url', 
     'categories_id', 
     'singers_id', 
     'types_id', 
    ]; 

    public function category() 
    { 
     return $this->belongsTo(CategoryModel::class, 'categories_id'); 
    } 
} 

CategorySongController

class CategorySongController extends Controller 
{ 

    public function index(CategoryModel $categoryModel) 
    { 
     $song = $categoryModel->song; 
     return response()->json(['Data' => $song]); 
    } 

} 

エラー

SQLSTATE [42S22]:カラム見つかりません:1054不明列 'songs.category_model_id' 'WHERE句'(SQLの中で: songsから選択*ここで、songsです。 category_model_idはヌルで、 songsです。 category_model_idマイルート

ルート)

ヌルでない::リソース( '/ API/V1 /カテゴリ'、 'C​​ategoryController'、[ 'のみ' => [ 'インデックス'、 ' show '、]]); Route :: resource( '/ api/v1/categories.songs'、 'CategorySongController'、['only' => ['index']]);あなたがあなたの関係に任意の外部キーを提供しなかったので、

+0

hasManyの(SongModel ::クラス)>の$ this - を返す '置き換える;' 'しますreturn $ this-で> hasManyの(SongModel ::クラス、 'categories_id');' –

+0

私は変わったが、それは再び私を示していますの使用定義されていない定数categories_id - 仮定 'categories_id' – Vichit

+0

quotesでcategories_idをラップしましたか? –

答えて

0

問題がCategoryModelモデルでは、あなたのsong関係にあり、現在の方法は

が復帰$this->hasMany(SongModel::class,'categories_id');にしてreturn $this->hasMany(SongModel::class);を置き換えるsongs表にcategory_model_idを見つけようとしますエラーを修正してください

0

songs()にCategoryModelのメソッドsong()を変更してみてください。

関連する問題