You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8中updateOrCreate报错:未知列'id',求问题排查与解决

Laravel 8 数据更新/插入功能报错修复

你遇到的错误 SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause',核心是主键配置错误+updateOrCreate逻辑错误,结合你的需求(根据machine_name判断新增或更新number_of_shifts),以下是具体问题和修复方案:

1. 模型未指定自定义主键

你的machines表主键是machine_id,但Laravel模型默认使用id作为主键字段,导致框架执行查询时找不到id列。

修复:在Machine模型中定义主键

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Machine extends Model
{
    use HasFactory, SoftDeletes;

    // 指定表的主键字段
    protected $primaryKey = 'machine_id';
    // 允许批量赋值的字段(必须指定,否则updateOrCreate会报错)
    protected $fillable = ['machine_name', 'number_of_shifts'];
}

2. updateOrCreate 参数逻辑错误

updateOrCreate的第一个参数是查询匹配条件,用来判断记录是否存在。你当前用number_of_shifts作为匹配条件,完全不符合需求(需求是根据machine_name判断)。

修复:修正updateOrCreate的参数逻辑

<?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' => 'required|string|max:255',
            'number_of_shifts' => 'required|integer|min:0',
        ]);

    // 第一个数组:匹配条件(根据machine_name查找记录)
    // 第二个数组:要更新/插入的数据(仅更新number_of_shifts,避免覆盖其他字段)
    Machine::updateOrCreate(
        ['machine_name' => $data['machine_name']],
        ['number_of_shifts' => $data['number_of_shifts']]
    );

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

3. 表单输入优化(可选)

number_of_shifts是数字类型,把blade模板里的input类型从text改为number,提升用户体验:

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

内容的提问来源于stack exchange,提问作者Андрей Быковский

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:30:48