Laravel将数据保存到两个位置

时间:2019-12-05 17:50:27

标签: php laravel

我正在做一个larvel项目,用户可以在其中创建约会。此外,我还创建了另一个名为客户端的模型,因此当用户创建约会时,将保存用户的“客户端”数据。

在我的约会控制器中,我有以下内容:-

  public function store(Request $request)
    {

        $this->validate($request, [
            'name' => 'required',
        ]);

        //create appointment
        $apt = new Appointment;
        $apt->name = $request->input('name');
        $apt->user_id = auth()->user()->id;
        $apt->save();

        //create client
        $client = new Client;
        $client->first_name = $request->input('name');
        $client->user_id = auth()->user()->id;
        $client->save();

        return redirect('/appointments')->with('success', 'Appointment created');
    }

保存数据时,它可以工作并将数据存储在客户表中,但是我知道这不是保存数据的最干净的方法,但是这样做的“ laravel”方法是什么?

1 个答案:

答案 0 :(得分:0)

您的代码没有错。保持这种方式完全没问题。

我更喜欢说Model :: create()在一条语句中创建模型。

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
    ]);

    Appointment::create([
        'name' => request('name'),
        'user_id' => auth()->id()
    ]);

    Client::create([
        'first_name' => request('name'),
        'user_id' => auth()->id,
    ]);

    return redirect('/appointments')->with('success', 'Appointment created');
}

您还可以使用tap()函数:

public function store(Request $request)
{
    $this->validate($request, [
        'name' => 'required',
    ]);

    tap(Appointment::create(['name' => request('name'), 'user_id' => auth()->id()]), function ($newAppoinment) {
        Client::create([
            'first_name' => $newAppoinment->name,
            'user_id' => auth()->id,
        ]);

    });

    return redirect('/appointments')->with('success', 'Appointment created');
}

或者最好的方法可能是使用model events

class Appointment extends Model
{
    public static function boot()
    {
        parent::boot();

        static::created(function ($appointment) {
            Client::create([
                'user_id' => $appoinment->user_id,
                'first_name' => $appoinment->name, 
            ])
        });
    }
}

相关问题