2张桌子形式为Laravel

时间:2016-11-04 06:36:42

标签: php laravel

我有两张桌子。 driver和part_time_available,当我选择驱动程序类型parttime时,它会显示part_time_available字段。问题是我无法保存。

它会抛出此错误:违反完整性约束: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');
    }

}

任何想法?

1 个答案:

答案 0 :(得分:1)

看看这里:

            $pta['driver_id'] = isset($pta['driver_id']) ? $pta['driver_id'] : null;
            $driver = Driver::find($pta['driver_id']);

从这个代码块我们可以看到driver_id可以是null。在这种情况下,没有找到的驱动程序。如果您有id,则应该只搜索驱动程序。