Laravel 多對多關聯模型 CURD 詳解

13122826258發表於2019-05-09
###   一個使用者可以有多個不同的角色;
###   一個角色會擁有各種不同的使用者;

-----

#### 角色資料表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 協議》,轉載必須註明作者和本文連結

相關文章