簡體   English   中英

更新或創建 - Laravel 8

[英]updateOrCreate - Laravel 8

剛開始學習Laravel,不知道怎么更新表中的數據。 這里有張桌子:

在此處輸入圖像描述

我想插入條目:machine_name + number_of_shifts。 同時,如果有 machine_name 記錄,那么必須為這條記錄更新 number_of_shifts 值。 或者,如果沒有記錄,則創建一個新的 machine_name + number_of_shifts。

結果,錯誤:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update `machines` set `machine_name` = Станок 456, `machines`.`updated_at` = 2023-01-16 20:52:34 其中 `id` 為空)

我開錯了什么????? 請幫我弄清楚。

Controller 代碼存儲控制器:

<?php

namespace App\Http\Controllers\Machines;

use App\Http\Controllers\Controller;
use App\Models\Machine;
use Illuminate\Http\Request;

class StoreController extends Controller
{
   public function __invoke(Request $request){


    $data = request()->validate([
            'machine_name' => '',
            'number_of_shifts' => '',
        ]);

 Machine::updateOrCreate(['number_of_shifts' => $request->input('number_of_shifts')], $data);

        return redirect()->route('machine.index');
    }

}

代碼創建.blade

@extends('layouts.main')

@section('title-block') Добавить станок @endsection

@section('content')

<div class="d-flex p-2">

<form action="{{ route('machine.store') }}" method="post">
@csrf


  <div class="mb-3">
    <label for="machine_name" class="form-label">Станок</label>
    <input type="text" name="machine_name" class="form-control" id="machine_name" placeholder="Станок 1">
  </div>
  
  <div class="mb-3">
    <label for="number_of_shifts" class="form-label">Количество смен</label>
    <input type="text" name="number_of_shifts" class="form-control" id="number_of_shifts" placeholder="1">
  </div>

  <button type="submit" class="btn btn-dark">Добавить станок</button>

  <a class="btn btn-dark" href="{{ route ('machine.index') }}" role="button">Назад</a>

</form>

</div>

@endsection

遷移代碼:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('machines', function (Blueprint $table) {
            $table->id('machine_id');
            $table->string('machine_name', 255);
            $table->bigInteger('number_of_shifts')->unsigned()->nullable()->default(0);
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('machines');
    }
};

如果您更改了主鍵名稱,那么您最常在 model 中這樣定義。

protected $primaryKey = 'machine_id';

這是更改其主鍵的壞主意。

暫無
暫無

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

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