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 协议》,转载必须注明作者和本文链接
有梦想的人睡不着,没有梦想的人睡不醒。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 1

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

1年前 评论

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!