我使用Laravel 5.8作为端点,使用Angular 7作为前端。
我有三个表:组(模型:Group),用户(模型:User)和users_group(模型:UserGroup)
组:ID,组名 用户:ID电子邮件,名称,密码 UserGroup:user_id,group_id
public function returnResponse($success, $data, $errorCode = 0, $message = false) {
$response = array();
$response['success'] = $success;
$response['message'] = isset($message) ? $message : '';
if ($errorCode) {
$response['errorCode'] = isset($errorCode) ? $errorCode : 0;
}
$response['data'] = $data;
return response()->json($response, 200);
}
public function register(Request $request)
{
$validation = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users|max:255',
'password' => 'required|confirmed|min:8|max:20',
]);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
$success = array();
$success['user_id'] = $user->id;
$success['user']=$user;
return $this->returnResponse(true, $success, 0, 'User registered successfully');
}
路线: api.php
Route::post('register', 'ApiController@register');
我想从Laravel为Angular生成一个端点。 一个用户可以属于多个组。对于要创建的用户,请选择组,然后将选择该组的ID。将用户注册保存到用户表时,user_id和group_id将保存到UserGroup中。
如何修改上面的当前代码以实现此目的?
答案 0 :(得分:0)
我认为group_id是根据请求发送的
public function register(Request $request)
{
$validation = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users|max:255',
'password' => 'required|confirmed|min:8|max:20',
]);
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->save();
UserGroup::create(['user_id' => $user->id, 'group_id' => $request->group_id]);
$success = array();
$success['user_id'] = $user->id;
$success['user']=$user;
return $this->returnResponse(true, $success, 0, 'User registered successfully');
}