我想用Laravel响应JSON,我有CategoryModel属于SongModel。Laravel 5.4如何用关系响应JSON?
这是我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);
}
}
我要回应JSON与关系。我写道:
class SongController extends Controller
{
public function index(SongModel $songModel)
{
$song = $songModel->category()->get();
return response()->json(["DATA" => $song], 201);
}
}
这说明我这个样子:{ “DATA”:{ “类别”:空 }} – Vichit
@Vichit哦,我明白了。也许在你的控制器中'$ songModel'为空,所以它在响应中返回null。 –
我认为你的代码路由模型绑定定义不正确。 –