私は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 /カテゴリ'、 'CategoryController'、[ 'のみ' => [ 'インデックス'、 ' show '、]]); Route :: resource( '/ api/v1/categories.songs'、 'CategorySongController'、['only' => ['index']]);あなたがあなたの関係に任意の外部キーを提供しなかったので、
hasManyの(SongModel ::クラス)>の$ this - を返す '置き換える;' 'しますreturn $ this-で> hasManyの(SongModel ::クラス、 'categories_id');' –
私は変わったが、それは再び私を示していますの使用定義されていない定数categories_id - 仮定 'categories_id' – Vichit
quotesでcategories_idをラップしましたか? –