我刚开始学Laravel,不知道怎么更新表格里的数据,有个表格:
我想插入条目:machine_name + number_of_shifts。同时,如果存在machine_name记录,则必须更新此记录的number_of_shifts值。或者,如果没有记录,则创建新的machine_name + number_of_shifts。
因此,错误:数据库状态[42 S22]:未找到列:1054“where子句”中的列“id”未知(SQL:更新'机器'集合'机器名称'= Станок 456,'机器'.'更新时间'= 2023-01-16 20:52:34其中'id'为空)
我开错了什么药?????请帮我弄清楚。
控制器代码存储控制器:
<?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');
}
};
1条答案
按热度按时间3bygqnnd1#
如果您已经更改了主键名称,那么您最好像这样在模型中定义。
而改变它的主键是个坏主意。