API RESTful Laravel 6.x多对多关系的最佳实践 [英] API RESTful Laravel 6.x Best Practice for Many to Many Relatioship

查看:50
本文介绍了API RESTful Laravel 6.x多对多关系的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Laravel 6开发API.

I'm developing an API with Laravel 6.

我有2种型号:

card->带有card_id ecc的桌卡.

card -> table cards with card_id ecc.

user->表具有user_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');
}

数据透视表称为card_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'
]);

但是当我需要存储信息时,我需要将卡和用户的ID传递到URL中,并作为帖子正文中的对象,如下所示:

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
]

存在更好的方法吗?

非常感谢!

推荐答案

您可以按以下说明使用嵌套资源: https://laravel.com/docs/6.x/controllers#restful-nested-resources

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');

此路线将注册一个嵌套"资源,可以使用以下URL进行访问:photos/{photos}/comments/{comments}."

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆