簡體   English   中英

盡管 API 成功傳入 postman,但數據未存儲在數據庫中

[英]Data is not stored in database eventhough API successfully passed in postman

我正在嘗試從前端(flutter)通過 API 存儲歷史數據。 下面是laravel中的controller。當我在postman中運行我的代碼時,它應該可以工作,因為當我發送請求時確實出現了消息“suksess add data”並且date_checkIn,time_checkIn都被記錄在這里https://粘貼.pics/f31592f51f63a5f77af77b0c0ad1e555 但是,當我簽入我的數據庫時,date_checkIn、time_checkIn 和 location_checkIn 列是 NULL 並且只記錄了staff_id 、created_at、updated_at 列。 當我嘗試在 postman 中重復請求但更改 location_checkIn 時,attendance_record 表中出現一條新記錄,顯示相同的結果,但現在有 2 個相同staff_id並且還記錄了 created_at 和 updated_at 列。

每次用戶從前端(顫動)打卡時,我都想存儲記錄。 我該如何解決?

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);
    }

更新用戶數據時,您仍然需要字段 ID。 您可以通過在其中添加“id”來更改您的一些 select 語句:

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

之后,go到你的AttendanceRecord model,將字段id添加到guarded。

protected $guarded = ['id'];

之后,您可以嘗試再次運行端點。 它應該被更新。

但是,如果您不想將 guarded 添加到您的 AttendanceRecord model 中,則應將檢索當前數據時的代碼更改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM