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

Laravel报错:未知列'id',如何将默认主键改为'id_produit'?

解决Laravel删除操作时主键不匹配的SQL错误

你的问题根源是Laravel Eloquent模型默认使用id作为表的主键,但你的produits表主键是id_produit,导致执行destroy()时SQL语句错误。只需修改Produit模型指定主键即可解决:

步骤1:修改Produit模型

在你的Produit模型文件(通常位于app/Models/Produit.php)中添加以下属性:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Produit extends Model
{
    // 自定义表主键字段名
    protected $primaryKey = 'id_produit';
    
    // 声明主键为自增类型(因为迁移中用了increments,所以必须保持true)
    public $incrementing = true;
}

补充说明

  • Laravel默认假设主键是自增int类型,如果你用的是非自增主键(比如字符串UUID),才需要额外设置$keyType = 'string'并将$incrementing设为false,你的场景不需要这一步。
  • 若使用路由模型绑定,可以简化destroy方法写法,直接接收模型实例(Laravel会自动根据id_produit查找对应记录):
public function destroy(Produit $produit)
{
    $produit->delete();
    return redirect('produits')->with('flash_message', 'produits deleted!');
}

(注:你原代码中的lash_message应为flash_message的笔误,建议修正)

内容的提问来源于stack exchange,提问作者aziz samouh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:53:15