我有两个表,我想用外键响应数据。
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:select * from
songs
songs
category_model_id
。songs
为空category_model_id
。24h_volume_usd
不为空)
我的路线
路由::资源(' / api / v1 / categories',' CategoryController',[' only' => [' index',' show',]]);路线::资源(' /api/v1/categories.songs' ;, ' CategorySongController',[' only' => ['指数']]);
答案 0 :(得分:0)
问题出在song
模型中的CategoryModel
关系中,您当前的方法会尝试在category_model_id
表中找到songs
,因为您没有提供任何外键在你们的关系中
使用返回return $this->hasMany(SongModel::class);
替换$this->hasMany(SongModel::class,'categories_id');
以修复错误
答案 1 :(得分:0)
尝试将CategoryModel中方法signature': b'<signature'>
的名称更改为复数'signature': signature_b64.decode('utf-8')
。