我在结构DB的列中为单个DB定义了slug。当我在路线上打电话时,我可以从路线上的另一个模型(例如这里的结构)中获取slu g吗?
路线是:
localhost:8000/api/singles/firstTest
我在Single模型中定义了getRouteKeyName函数:
public function structure()
{
return $this->belongsTo(Structure::class);
}
public function getRouteKeyName()
{
return $this->structure()->select('slug')->first();
}
在您的控制器中,如果您指定了以下路线,您将获得firstTest
作为路线参数:
Route::get('api/singles/{slug}', 'SomeController@someAction');
然后控制器:
public function someAction(Request $request, $slug)
{
// Perform validations and policy authorization if required
$id = Single::whereHas('structure', function ($query) use($slug) {
$query->where('slug', '=', $slug);
})->first();
if(!$id){
abort(404);
}
// Process the data using $id obtained above
}