【发布时间】:2017-08-09 17:57:52
【问题描述】:
我有两个表,我想用外键响应数据。
表格类别
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id',10);
$table->string('name',100)->nullable();
$table->timestamps();
});
}
桌歌
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');
});
}
类别模型
class CategoryModel extends Model
{
protected $table = 'categories';
protected $fillable = [
'id',
'name',
];
public function song()
{
return $this->hasMany(SongModel::class);
}
}
歌曲模型
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 未知列 'where 子句'中的'songs.category_model_id'(SQL:select * from
songs其中songs.category_model_id为空且songs.category_model_id不为空)
我的路线
Route::resource('/api/v1/categories', 'CategoryController', ['only' => ['索引', '显示',]]); Route::resource('/api/v1/categories.songs', 'CategorySongController', ['only' => ['index']]);
【问题讨论】:
-
用
return $this->hasMany(SongModel::class,'categories_id');替换return $this->hasMany(SongModel::class); -
我改变了,但它再次显示:使用未定义的常量 categories_id - 假定为 'categories_id'
-
你用引号包裹了 categories_id 吗?
-
对不起先生,云你解释一下?
-
你能告诉我你添加的整行代码吗?