API RESTful Laravel 6.x 多对多关系的最佳实践 [英] API RESTful Laravel 6.x Best Practice for Many to Many Relatioship
问题描述
我正在使用 Laravel 6 开发 API.
我有两个模型:
<块引用>card -> 带有 card_id ecc 的桌卡.
user -> user_id 为 ecc 的表用户.
我已经定义了多对多关系的模型
用户.php
公共功能卡(){返回 $this->belongsToMany('App\Models\v1\Card');}
卡片.php
公共函数 users() {返回 $this->belongsToMany('App\Models\v1\User');}
数据透视表称为 card_user .
现在我已经为单个实体创建了路由:
Route::resource('v1/users', 'v1\UsersController');Route::resource('v1/cards', 'v1\CardsController');
我需要开发路由和控制器,以便从数据透视表中插入和删除行.
解决此问题的最佳做法是什么?
我尝试使用响应特定端点的特殊控制器来解决此问题:
Route::resource('v1/cards/{id}/users', 'v1\CardsUsersController')->only([索引"、存储"、销毁"]);
但是当我需要存储信息时,我需要将卡片和用户的 id 传递到 URL 中,并作为帖子正文中的对象,如下所示:
<预><代码>['user_id' =>$用户ID,'card_id' =>$cardId]是否有更好的方法来做到这一点?
非常感谢!
您可以使用嵌套资源,如下所述:https://laravel.com/docs/6.x/controllers#宁静的嵌套资源
有时您可能需要定义到嵌套"资源的路由.例如,一个照片资源可能有多个评论"可能附加到照片上.要嵌套"资源控制器,请使用点"表示法在您的路线声明中:
Route::resource('photos.comments', 'PhotoCommentController');
此路由将注册一个嵌套"资源,可以使用如下 URL 访问该资源:photos/{photos}/comments/{comments}."
I'm developing an API with Laravel 6.
I've got 2 models:
card -> table cards with card_id ecc.
user -> table users with user_id ecc.
I've defined into models many to many relationships
User.php
public function cards()
{
return $this->belongsToMany('App\Models\v1\Card');
}
Card.php
public function users() {
return $this->belongsToMany('App\Models\v1\User');
}
The pivot table is called card_user .
Now I've created routes for single entities:
Route::resource('v1/users', 'v1\UsersController');
Route::resource('v1/cards', 'v1\CardsController');
and I need to develop routes and controller for insert and delete rows from pivot table.
What is the best practice for this issue?
I try to solve this with a special controller that respond to a specific endpoint:
Route::resource('v1/cards/{id}/users', 'v1\CardsUsersController')->only([
'index', 'store', 'destroy'
]);
But when I need to store information I need to pass the ids of card and user into the URL and as object in post body like so:
[
'user_id' => $userId,
'card_id' => $cardId
]
Exists a better way to do this?
Thanks a lot!
You can use Nested Resources as described here: https://laravel.com/docs/6.x/controllers#restful-nested-resources
"Sometimes you may need to define routes to a "nested" resource. For example, a photo resource may have multiple "comments" that may be attached to the photo. To "nest" resource controllers, use "dot" notation in your route declaration:
Route::resource('photos.comments', 'PhotoCommentController');
This route will register a "nested" resource that may be accessed with URLs like the following: photos/{photos}/comments/{comments}."
这篇关于API RESTful Laravel 6.x 多对多关系的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!