我目前有两个表,即存储用户和客户端。客户端以一对一的关系与用户相关。
我目前正在存储和更新模型,但感觉相当笨重...
public function store(Request $request)
{
$requestData = $request->all();
$user = new User();
$user->fill($requestData);
$user->save();
$client = new Client;
$client->fill($requestData);
$client->user()->associate($user);
$client->save();
return response()->json($client->toArray(), 201, ['id' => $client->id]);
}
public function update(Request $request, $id)
{
try {
$client = Client::findOrFail($id);
$user = User::findOrFail($client->fk_user);
} catch (ModelNotFoundException $e) {
return response()->json([
'error' => [
'message' => 'Client not found',
]
], 404);
}
$requestData = $request->all();
$user->fill($requestData);
$user->save();
$client->fill($requestData);
$client->user()->associate($user);
$client->save();
return response()->json($client->toArray(), 200);
}
有没有办法重构这一点,以避免作为单独的模型同时使用用户和客户端。有没有办法可以填充客户端,然后填充父用户模型?
只是想知道,谢谢!
答案 0 :(得分:1)
我为你做了一些重构灵感。这不一定是“正确的”方式,但也许你可以选择你喜欢的东西。
请注意!我实际上没有测试过代码,它可能充满了语法错误。我只是将其砍下来以显示一些想法。一些逻辑,比如关联用户,我想象放在客户端模型中。错误处理发生在app / Exceptions / Handler.php。
中希望你可以使用它:)
private function saveUser($args, $user = null) {
$user = $user ?: new User();
$user->fill($args);
$user->save();
return $user;
}
private function saveClient($args, $client= null) {
$client = $client ?: new Client;
$client->fill($args);
$client->save();
return $client;
}
private function respondCreated($data = []) {
return $this->respond($data, 201, "created");
}
private function respond($data = [], $statusCode = 200, $message = "ok") {
$response = [
"message" => $message,
"data" => $data
];
return response()->json($response, $statusCode);
}
public function store(Request $request)
{
$user = $this->saveUser($request->all());
$client = $this->saveClient($request->all());
$client->saveUser($user);
return $this->respondCreated($client);
}
public function update(Request $request, $id)
{
$client = $this->saveClient($request->all(), $client::findOrFail($id));
$this->saveUser($request->all(), $client->fk_user);
return $this->respond($client);
}