laravel 即使在postman中成功传递API,数据也不会存储在数据库中

lyfkaqu1  于 2022-12-05  发布在  Postman
关注(0)|答案(1)|浏览(224)

我尝试通过前端的API存储历史数据(flutter)。下面是laravel中的控制器。当我在postman中运行我的代码时,它应该工作,因为当我发送请求时确实出现了消息“sukessadddata”,并且date_checkIn、time_checkIn都被记录为https://paste.pics/f31592f51f63a5f77af77b0c0ad1e555。但是,当我在数据库中检查时,date_checkIn、time_checkIn并且location_checkIn列为NULL,并且只记录了 staff_id、created_at、updated_at列。当我尝试在postman中重复请求但更改location_checkIn时,attendment_record表中出现一条新记录,显示相同的结果,但现在有两条 * 相同的**staff_id*,并且还记录了created_at和updated_at列。
我想存储记录每次用户 * 打卡 * 从前端(Flutter)。我如何解决这个问题?

public function userClockIn(Request $r)
    {
        $result = [];
        $result['status'] = false;
        $result['message'] = "something error";

        $users = User::where('staff_id', $r->staff_id)->select(['staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first();

        $mytime = Carbon::now();
        $time = $mytime->format('H:i:s');
        $date = $mytime->format('Y-m-d');

        // Retrieve current data
        $currentData = $users->toArray();

        // Store current data in attendance record table
        $attendanceRecord = new AttendanceRecord();
        $attendanceRecord->fill($currentData);
        $attendanceRecord->save();

        $users->date_checkIn = $date;
        $users->time_checkIn = $time;
        $users->location_checkIn = $r->location_checkIn;

        $users->save();

        $result['data'] = $users;
        $result['status'] = true;
        $result['message'] = "suksess add data";

        return response()->json($result);
    }
elcex8rz

elcex8rz1#

更新用户数据时仍需要字段ID。您可以通过在select语句中添加**'id'**来更改某些select语句:

$users = User::where('staff_id', $r->staff_id)->select(['id', 'staff_id', 'date_checkIn', 'time_checkIn', 'location_checkIn'])->first();

之后,转到你的AttendanceRecord模型,将字段id添加到守护中。

protected $guarded = ['id'];

之后,您可以尝试再次运行端点。它应该会被更新。
但是如果你不想把保护加入到你的AttendanceRecord模型中,你应该在检索当前数据时改变你的代码成:

$currentData = [
        "staff_id" => $users->staff_id,
        "date_checkIn" => $users->date_checkIn,
        "time_checkIn" => $users->time_checkIn,
        "location_checkIn" => $users->location_checkIn,
    ];

相关问题