为什么当我更新特定记录时会添加新记录?

Why when I update a specific record a new record is added?

当我更新特定记录时,记录没有更新,但是它添加了一条新记录并且记录没有更新。
我使用 updateOrCreate() 是因为我使用一种模式来添加和更新,并且我使用 ajax 将数据传递给控制器​​。 只是想让你知道我有一个外键,它是 airlineId,如果这可能有帮助的话。

ajax:

 $('body').on('click', '#btn-save', function (event) {
          var id = $("#id").val();
          var flightDesignator = $("#flightDesignator").val();
          var departureFrom = $("#departureFrom").val();
          var arriveTo = $("#arriveTo").val();
          var departureTime = $("#departureTime").val();
          var ArrivalTime = $("#ArrivalTime").val();
          var airlineId = $("#airlineId").val();
          $("#btn-save").html('Please Wait...');
          $("#btn-save"). attr("disabled", true);
         
       
       
        $.ajax({
            type:"POST",
            url: "{{ url('admin/add-update-flights') }}",
            data: {
              id:id,
              flightDesignator:flightDesignator,
              departureFrom:departureFrom,
              arriveTo:arriveTo,
              departureTime:departureTime,
              ArrivalTime:ArrivalTime,
              airlineId:airlineId,
            },
            dataType: 'json',
            success: function(res){
             window.location.reload();
            $("#btn-save").html('Submit');
            $("#btn-save"). attr("disabled", false);
            Swal.fire(
            'Good job!',
            'You clicked the button!',
            'success'
            )
           }
        
        });
      
    });

控制器:

public function store(Request $request)
    {
        $Flight   =   Flight::updateOrCreate(
            [
                'FlightId' => $request->id
            ],
          
           
            [
                'flightDesignator' => $request->flightDesignator, 
                'departureFrom' => $request->departureFrom,
                'arriveTo' => $request->arriveTo,
                'departureTime' => $request->departureTime, 
                'ArrivalTime' => $request->ArrivalTime,
                'airlineId' => $request->airlineId,
            ]);
     
                 return response()->json(['success' => true]);
    }


 public function edit(Request $request)
    {   
        $where = array('FlightId' => $request->id);
        $flight  = Flight::where($where)->first();
 
        return response()->json($flight);
    }

轻松修复

if($request->id)
{
 $Flight   =   Flight::find($request->id);
}
else{
  $Flight = new Flight();
}

$Flight->flightDesignator = $request->flightDesignator;
/* remaing data*/
$Flight->save();

return response()->json(['success' => true]);
$update_value = YourModel::updateOrCreate(
    ['your_checking_column' => 'your_value',],
    ['your_updated_coumn' => 'your_updated_value']
);

这里先检查$request->id的值。 如果值为空,updateOrCreate() 将创建一条记录而不是更新现有记录。