Laravel路由中的常見設置是使用嵌套資源和路由模型綁定。這允許偉大的邏輯URL來表示模型在數據庫中相互之間的實際關係。這可能是/ library/section/book /的一個例子。該書由該部分擁有,該部分由圖書館擁有。但是當使用路由模型綁定時,這些資源的id會變成沒有任何其他知識的模型。/1/7/234將返回這些資源的模型,但不能保證它們有適當的關聯。書籍234可能不屬於第7部分,第7部分可能不屬於圖書館1。我經常在每個控制器的頂部有一個方法來處理檢查我所稱的關係測試。這個功能可以在Book控制器中找到。從嵌套資源檢查模型關係
private function relationshipCheck($library, $section, $book)
{
if(library->id == $section->library_id) {
if($book != false) {
if($section->id == $book->section_id) {
return true;
} else {
return response()->json(["code" => 401], 401);
}
} else {
return true;
}
} else {
return response()->json(["code" => 401, 401);
}
}
什麼是正確的方式來處理使用這些代表關係的路線?有沒有更自動化的方式來做到這一點?當關系都是一對多關係時,是否有理由忽視所有內容,而不是最後一個資源?