php - Laravel 将数据保存到两个位置
问题描述
我正在开发一个用户可以创建约会的 larvel 项目。此外,我还创建了另一个名为 clients 的模型,因此当用户创建约会时,会保存用户的“client”数据。
在我的约会控制器中,我有以下内容:-
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”方法是什么?
解决方案
你的代码没有问题。保持这种状态完全没问题。
我更喜欢说 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');
}
或者最好的方法可能是使用模型事件:
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,
])
});
}
}
推荐阅读
- python - 使用 rsplit 从字符串末尾删除某些字母的单行器?
- regex - NLTK 正则表达式解析器的输出已更改。无法解析动词后跟名词之类的短语
- reactjs - 动态链接在 react-app 的构建中不起作用
- python - 如何在python中对字符串进行子串化?
- excel - VBA:将子程序包含在条件中
- android - 插页式广告关闭后如何进行下一个活动而不是相同的活动?
- javascript - Vue JS 2:在 beforeCreate 之后停止生命周期
- java - 将 Intellij 键盘设置映射到 Visual Studio
- karate - 如何根据条件将值为 Null 的新键添加到动态响应体中
- python - 没有找到 PyJWT<3.0.0,>=2.0.1 的匹配分布