php - Php Laravel 更新数据时添加了新记录
问题描述
嗨,当我尝试更新表中的数据而不是添加新记录时,我遇到了问题。我的更新方法是:
public function update(CompanyUpdateRequest $request, Company $company)
{
try{
$request['id'] = 1;
$this->companyService->setModel($company)->update($request->all());
$request->session()->flash('success', 'Nastavenie bolo zmenené!');
return redirect('admin/company');
}
catch(\Exception $e){
$request->session()->flash('warning', 'Nastavenie sa nepodarilo uložiť!' . $e);
return redirect('admin/company');
}
}
我的服务更新:
public function update(array $data, $modelOrId = null): BaseModelService
{
if ($modelOrId !== null) {
if ($modelOrId instanceof Model) {
$this->setModel($modelOrId);
} elseif (is_int($modelOrId)) {
$modelOrId = $this->getRepository()->find($modelOrId);
$this->setModel($modelOrId);
}
}
$this->getModel()->fill($data)->save();
//Here is the problem when i try to save
return $this;
}
在表中总会有一个公司,所以我需要总是更新 id 为 1 的记录。但是当我尝试更新时,如上图所示,id=1 我会收到消息重复主键。请问应该是哪里出了问题?
App\Company {#306 ▼
#table: "company"
#fillable: array:13 [▼
0 => "phone_number"
1 => "name"
2 => "email"
3 => "instagram"
4 => "facebook"
5 => "youtube"
6 => "gps"
7 => "address"
8 => "psc"
9 => "city"
10 => "house_number"
11 => "name_executive_manager"
12 => "surname_executive_manager"
]
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▼
0 => "*"
]
}
我的更新路线:
Route::put('/admin/company/{id}', 'Admin\CompanyController@update')->name('admin_company_update');
解决方案
问题出在路线上:不好的一个:
Route::put('/admin/company/{id}', 'Admin\CompanyController@update')->name('admin_company_update');
好一个:
Route::put('/admin/company/{company}', 'Admin\CompanyController@update')->name('admin_company_update');
刚换了公司的id
THX Md Juyel Rana 帮助我解决了这个问题
推荐阅读
- html - DITA 文档标题和其他字段值应显示在动态页眉或页脚中
- python - 我可以在这个 seaborn 热图中调整颜色条的比例吗?
- javascript - 网站可以跟踪用户是手动填写表格还是自动填写?
- algorithm - 如何从另一个时间段中删除一个时间段?
- java - 给定字符串的日期格式
- php - 如何使用来自 API 的响应进入控制器 - CodeIgniter
- django - 使用 Django 构建第三方 API
- pylint - pylint3 变量名“fl”不符合snake_case 命名风格(无效名称)
- sql-server - 我可以添加到 DDL 触发器插入/更新的表值吗?
- javascript - Vue-test-utils:如何模拟 VueX 中动作的返回?