您好,我正在try 做一个简单的删除功能,但它显示一个错误

以下是来自控制器的代码:

public function destroy($id)
{
    $clientOrder = ClientHasOrder::where('order_id',$id)->firstOrFail();
    $clientOrder->delete();
    return redirect('/')->with('msg','Order Deleted successfully!');
}

以下是型号代码:

class clientHasOrder extends Model
{
    use HasFactory;
    
    public $timestamps = false;
    
    protected $fillable = [
        'order_id',
        'product_id',
        'amount',
    ];
}

这是迁移文件:

public function up()
{
    Schema::create('client_has_orders', function (Blueprint $table)
    {
        $table->string('order_id')->constrained();
        $table->foreignId('product_id')->constrained();
        $table->string('amount')->default('200');
    });
}

当我单击删除按钮时,我收到以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' 
    
delete from
    `client_has_orders`
where
    `id` is null

用红色显示这条线:$clientOrder->delete();

当我将列的名称从order_id更改为id时,代码可以工作,但我不想将其命名为id

推荐答案

try 不使用FirstorFail(),因为您的表没有ID.

    public function destroy($id)
    {
        $clientOrder = clientHasOrder::where('order_id', $id)->delete();
        return redirect('/')->with('msg', 'Order Deleted successfully!');
    }

Laravel相关问答推荐

哈希:check()不返回预期结果Laravel 10

Laravel Horizo​​n 限制与优化

RuntimeException 未安装 Zip PHP 扩展

安卓 retrofit |发布自定义对象(将 json 发送到服务器)

Laravel + SQLite = SQLSTATE[HY000]一般错误:8次try 写入只读数据库

Guzzle - Laravel如何使用 x-www-form-url-encoded 发出请求

Carbon(laravel)处理无效日期

使用 Eloquent 的 Laravel 块方法

如何在 Laravel 中显示渲染时间/页面加载时间?

链接到容器时如何使用主机网络?

Laravel 表 * 没有名为 * 的列

在 laravel 5.2 中禁用特定路由的 Web 中间件

如何在新安装时指定 Lumen(或 Laravel)版本?

Laravel:验证 json 对象

Laravel Mix 生成字体到另一个目录

嘲笑没有匹配的关闭处理程序

在 Laravel 中软删除父记录时如何软删除相关记录?

Laravel 排序集合,然后按键

Laravel 更新查询

laravel:如何获取 eloquent 模型的列名?