Laravel 创建和更新具有外部关系的模型

Laravel create and update model with foreign relationship

我目前有两个表,分别存储用户和客户。客户与用户之间存在一对一关系。

我目前正在像这样存储和更新模型,但感觉很笨拙...

 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);
    }

有没有一种方法可以对此进行重构,以避免必须将用户和客户作为单独的模型来处理。有没有办法填充一个客户端,然后填充父用户模型?

只是想知道,谢谢!

我为您提供了一些重构灵感。这不一定是"right"方式,但也许你可以挑选你喜欢的东西。

注意!我还没有实际测试代码,它可能充满了语法错误。我只是把它砍下来以展示一些想法。一些逻辑,比如关联用户,我想象中放置在客户端模型中。错误处理发生在 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);
}