我知道这个问题可能完全是基于意见的,但是这里有。我想知道基于Laravel中模型关系构建路径的推荐方法。以以下三种模型为例:
User
Post
Comment
他们的关系(最基本的)如下:
User hasMany Posts
Post hasMany Comments
在我的rotes文件中,我希望获得特定用户的帖子列表。我可能倾向于使用以下任何一种方法:
Route::get('/users/{user_id}/posts')
Route::get('/posts/{user_id}')
而且对于获取特定帖子的评论,我可以使用以下任何一个:
Route::get('/posts/{post_id}/comments')
Route::get('/comments/{post_id}')
哪种方法最值得推荐。为什么?谢谢你们!
你的第一个选择看起来很好
Route::get('/users/{userId}/posts')
Route::get('/posts/{postId}/comments')
如果要实现“反向”端点,那么如何更明确地描述路由参数:
Route::get('/posts/by-user/{userId}')
Route::get('/comments/for-post/{postId}')