我有2个型号:类别和产品,类别模型与产品有hasToMany关系,产品与类别有属关系。我的路线是/ sports / some-slug-sports-article。 所以我关心的是如何用slug rout而不是id绑定我的Model。这是我的代码:
Route::get('{category}/{article}', function ($category, $article) {
return view('test',compact('article'));
});
RouteServicePovider
Route::bind('category',function($category){
return $category = \App\Category::where('slug', $category)->firstOrFail();
});
Route::bind('article',function($article){
return \App\Article::where([['category_id',$category->id],['slug',$article],['status',1]])->firstOrFail();
});
答案 0 :(得分:0)
您可以指定关系使用哪些外键,因此您必须更改模型关系方法,如下所示:
$this->hasMany('App\Article', 'slug', 'article_slug');
// replace slug and article_slug with your foreign keys