Laravel 在 SQL 中插入数据不是函数使用错误的可能原因

Laravel inserting data in SQL not possible cause of wrong use of functions

我试图计算入住和退房之间的时差,但不知何故它不起作用。我很确定我做错了什么,但我无法理解它。

SQLSTATE[HY000]: General error: 1364 Field 'hours' doesn't have a default value (SQL: insert into times (workers_workid, checkin, checkout) values (110001, 2022-03-09T18:22, 2022-03-09T23:22))

控制器

class TimeController extends Controller
{
    function addData(Request $req)
    {
        $time = new Time;
        $time->workers_workid = $req->worker;
        $time->checkin = $req->checkintimestamp;
        $time->checkout = $req->checkouttimestamp;
        $time->save();
        $time->hours = $this->saveData($this->worker, $this->checkintimestamp, 
            $this->checkouttimestamp);
        $time->save();
    }

    public function saveData($id, $cIn, $cOut)
    {
        $rec = Time::create([
            'workers_workid' => $id,
            'checkin' => Carbon::parse($cIn),
            'checkout' => Carbon::parse($cOut),
        ]);
        $rec['hours'] = $rec['checkout']->floatDiffInHours($rec['checkin']);
        $rec->save();

        return $rec;
    }
}

迁移

class CreateTimesTable extends Migration
{
    public function up()
    {
        Schema::create('times', function (Blueprint $table) {
            $table->id();
            $table->integer('workers_workid')->unsigned()->nullable();
            $table->dateTime('checkin');
            $table->dateTime('checkout');
            $table->float('hours');
            $table->foreign('workers_workid')
                ->references('workid')
                ->on('workers')
                ->onDelete('cascade');
        });
    }
}

create()方法立即保存记录。您需要调整您的逻辑以确保 hours 在 调用之前填充

public function addData(Request $request) {
  $checkin = Carbon::parse($request->checkintimestamp);
  $checkout = Carbon::parse($request->checkouttimestamp);
  $hours = $checkout->floatDiffInHours($checkin);

  return Time::create([
    'workers_workid' => $request->worker,
    'checkin' => $checkin,
    'checkout' => $checkout,
    'hours' => $hours
  ]);
}

旁注:您的 saveData() 方法是多余的,可以删除。

还有其他方法,例如 $rec = new Time();,添加字段 one-by-one,然后调用保存:

public function addData(Request $request) {
  $time = new Time();

  $time->workers_workid = $request->worker;
  $time->checkin = Carbon::parse($request->checkintimestamp);
  $time->checkout = Carbon::parse($request->checkouttimestamp);
  $time->hours = $time->checkout->floatDiffInHours($time->checkin);

  $time->save();

  return $time;
}