它会抛出此错误:违反完整性约束:1048列' driver_id'不能为空
这是我到目前为止的保存控制器代码:
public function save(Request $request, $obj = null) {
if (!$obj) {
$obj = new Driver;
}
$obj->active = TRUE;
$obj->counter = 0;
return $this->saveHandler($request, $obj);
}
public function saveHandler(Request $request, $obj)
{
try {
DB::beginTransaction();
$obj->fill($request->all());
if (!$obj->save()) {
throw new ValidationException($obj->errors());
}
foreach($request->parttimeAvailabilities as $pta) {
if (empty($pta['id'])) {
$parttimeAvailability = new ParttimeAvailability();
}
else {
$parttimeAvailability = ParttimeAvailability::find($pta['id']);
}
$parttimeAvailability->Driver()->associate($obj);
$pta['driver_id'] = isset($pta['driver_id']) ? $pta['driver_id'] : null;
$driver = Driver::find($pta['driver_id']);
$parttimeAvailability->driver()->associate($driver);
$parttimeAvailability->day = $pta['day'];
$parttimeAvailability->start_time = $pta['start_time'];
$parttimeAvailability->end_time = $pta['end_time'];
$parttimeAvailability->available = isset($pta['available']);
$parttimeAvailability->save();
};
$obj->save();
if (!$parttimeAvailability->save()) {
throw new ValidationException($parttimeAvailability->errors());
}
DB::commit();
return $this->sendSuccessResponse($request);
} catch (ValidationException $e) {
DB::rollback();
\Log::error($e->errors);
return $this->sendErrorResponse($request, $e->errors);
} catch (Exception $e) {
DB::rollback();
\Log::error($e->getMessage());
return $this->sendErrorResponse($request,'Unable to process. Please contact system Administrator');
}
}
任何想法?
答案 0 :(得分:1)
看看这里:
$pta['driver_id'] = isset($pta['driver_id']) ? $pta['driver_id'] : null;
$driver = Driver::find($pta['driver_id']);
从这个代码块我们可以看到driver_id
可以是null
。在这种情况下,没有找到的驱动程序。如果您有id,则应该只搜索驱动程序。