我有一个mySQL表,其中列有device_id
列的用户设备,其中分配了UNIQUE
个约束。
在我的Laravel应用程序中,我的APIController
类提供了一个API,用于向表中添加新设备。该方法如下所示:
public function postDevice(Request $request)
{
$user = Auth::user();
if(!$request->has('device_id'))
return response()->json(['error' => 'You need to provide a unique device identifier "device_id".'], 460);
$device_id = $request->input('device_id');
$device = UserDevice::where('device_id', $device_id)->first();
if($device) {
// update device properties with transmitted data
$device->fill($request->all());
// make sure this device belongs to our user
$device->user()->associate($user);
$device->save();
} else {
// create new device for our user
$user->devices()->create($request->all());
}
return response()->json(['status'=>'success']);
}
我认为我的条件会确保通过此API不会违反唯一性约束。但不知何故,我经常会遇到这样的错误:
Integrity constraint violation: 1062 Duplicate entry 'C02P69YWG3QC' for key 'user_devices_device_id_unique' (SQL: insert into 'user_devices' ('device_id', 'mac_model', 'mail_version', 'mailbutler_version', 'osx_version', 'user_id', 'updated_at', 'created_at') values (C02P69YWG3QC, MacBook Pro (Retina, 15-inch, Late 2013), 10.0 (3225), 6439, 10.12.0, 13400, 2016-09-13 12:17:56, 2016-09-13 12:17:56))
您是否知道如何使用上面显示的代码违反约束? 是否有更好的编码范例来避免这种错误?
顺便说一句:我正在运行此应用程序,可能有多个实例在同一个数据库上运行。是否会涉及竞争条件?
答案 0 :(得分:0)
为什么不使用验证?
$this->validate($request, [
'device_id' => 'bail|required|unique:user_devices',
]);