Laravel 多对多关联模型 CURD 详解

###   一个用户可以有多个不同的角色;
###   一个角色会拥有各种不同的用户;

-----

#### 角色数据表roles :id、name
####   用户数据表users : id、name
####   角色-用户数据表role_user : role_id、user_id

-----

User.php 模型

class User extends Model
{
  //指定批量更新字段
          protected $fillable = ['name'];

          public function roles()
         {
             //指定自定义命名生成关联表的键名,外键等
              return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
         }
 }

UserController 控制器
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
use App\Model\User;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
 {
/**
 * Display a listing of the resource.
 *
 * [[[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
 */
public function index()
{
    $users = User::get();
    foreach ($users as $user) {
        if ($user) {
            $user->roles;
        }
    }
    return response()->json([
        'message' => '请求成功',
        'data' => $users ?: []
    ], 200);
}

/**
 * Show the form for creating a new resource.
 *
 * [[[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
 */
public function create()
{
    //
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request $request
 * [[[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
 */
public function store(UserRequest $request)
{
    $users['name'] = $request->get('name');
    $role_ids = $request->get('role_id');
    DB::beginTransaction();
    try{
        $user = User::create($users);
        $user->roles()->attach($role_ids);

        DB::commit();
        return response()->json([
            'message' => '新增成功',
            'data' => $user
        ], 200);
    }catch (\Exception $e){
        DB::rollBack();
        return response()->json([
            'message' => '新增失败',
        ], 400);
    }
}

/**
 * Display the specified resource.
 *
 * @param  int $id
 * [[[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
 */
public function show($id)
{
    $user = User::find($id);
    if($user) {
        $user->roles;
    }

    return response()->json([
        'message' => '请求成功',
        'data' => $user ?: []
    ], 200);

}

/**
 * Show the form for editing the specified resource.
 *
 * @param  int $id
 * [[[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
 */
public function edit($id)
{
    //
}

/**
 * Update the specified resource in storage.
 *
 * @param  \Illuminate\Http\Request $request
 * @param  int $id
 * [[[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
 */
public function update(Request $request, $id)
{
    $user_name['name'] = $request->get('name');
    $role_ids = $request->get('role_id');
    DB::beginTransaction();
    try {
        $user = User::findOrFail($id);
        $user->update($user_name);
        $user->roles()->detach();//先删除关系
        $user->roles()->attach($role_ids);
        DB::commit();
        return response()->json([
            'message' => '更新成功',
            'data' => $id
        ], 200);
    } catch (\Exception $e) {
        DB::rollBack();
        return response()->json([
            'message' => '更新失败',
        ], 400);
    }
}

/**
 * Remove the specified resource from storage.
 *
 * @param  int $id
 * [[[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554)](https://learnku.com/users/31554) \Illuminate\Http\Response
 */
public function destroy($id)
{
    DB::beginTransaction();
    try {
        $user = User::findOrFail($id);
        $user->roles()->detach();
        $user->delete();
        DB::commit();
        return response()->json([
            'message' => '删除成功',
            'data' => $id
        ], 200);
    } catch (\Exception $e) {
        DB::rollBack();
        return response()->json([
            'message' => '删除失败',
        ], 400);
    }
}
}

 

本作品采用《CC 协议》,转载必须注明作者和本文链接
有梦想的人睡不着,没有梦想的人睡不醒。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 1

可以使用with .update有时候,可以使用sync();

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
88
粉丝
21
喜欢
134
收藏
267
排名:228
访问:4.2 万
私信
所有博文
博客标签
redis
1
php
1
laravel
7
docker
3
orm
2
sync
1
pivot
1
detach
2
attach
2
算法
1
递归
1
多对多
1
lnmp环境搭建
1
GO变量
1
GO数据类型
1
IOC注入反转
1
IOC容器的绑定解析过程(绑定单例)
1
原生微信网页授权登录(natapp穿墙)
1
VMwareNAT网卡配置
1
MySQL基础架构
1
redis 主从搭建
1
Sentinel哨兵模式解决故障转移
1
elasticsearch安装
1
elasticsearch集群安装3台
1
安装kibana
1
必须了解的mysql三大日志-binlog、redo log和undo log
1
何处理数据恢复 数据丢失 面试tx的架构师的岗位问的
1
分库分表插入数据
1
创建分库分表(在主从复制的基本上)
1
分库分表总结
1
mysql总结
1
haproxy状态检测脚本(完成高可用)
1
mysql高可用衡搭建(Keepalived)
1
mysql负载均衡搭建(haproxy)
1
mysql主从恢复数据一致性(pt工具-t-table-checksum和pt-table-sync)
1
终于解决了《====》记一次mysql热备份xtrabackup(没有解决问题)
1
mysql事务
1
MYSQL8.0安装
1
Redis-cluster分布式集群搭建部署
1
比Redis-cluster还好的redis分布式集群(twemproxy)
1
Redis缓存穿透/缓存雪崩/缓存击穿(案例:产生的原因 解决方案利/弊)
1
数据结构之MySQL独爱B+树(二叉树、AVL树、红黑树、B树对比)
1
B-tree
1
B+tree
1
Mycat实现mysql的负载均衡读写分离
2
mysql双主双从 搭建配置
1
mycat 双主双从-负载均衡-高可用
1
Mycat垂直分库
1
记一次mysql高可用技术分享
1
【rabbitmq】安装ampq的扩展的踩坑总结
1
PHP操作MongoDB(增删改查)
1
golang总结
5
社区赞助商