模型关系的推荐 Laravel 路由结构

Recommended Laravel route structure for model relationships

我知道这个问题可能完全是基于个人意见的,但请继续。我想知道 Laravel 中基于模型关系构建路由的推荐方法。以下面三个模型为例:

User
Post
Comment

他们的关系(最基本的)如下:

User hasMany Posts
Post hasMany Comments

在我的 rotes 文件中,我希望获得特定用户的帖子列表。我可能倾向于使用以下任何一种:

Route::get('/users/{user_id}/posts')
Route::get('/posts/{user_id}')

以及获取特定 post 的评论我可以使用两者中的任何一个:

Route::get('/posts/{post_id}/comments')
Route::get('/comments/{post_id}')

哪种方法最值得推荐。为什么?谢谢大家!

您的第一个备选方案看起来不错:

Route::get('/users/{userId}/posts')
Route::get('/posts/{postId}/comments')

如果你想实现"the inverse"端点,如何更明确地描述路由参数:

Route::get('/posts/by-user/{userId}')
Route::get('/comments/for-post/{postId}')