【问题标题】:Why the delete query execute Laravel为什么删除查询执行 Laravel
【发布时间】:2023-01-30 20:51:48
【问题描述】:

你好,我正在尝试制作一个简单的删除功能,但它显示错误

这是来自控制器的代码:

  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

【问题讨论】:

    标签: laravel


    【解决方案1】:

    在没有 firstorfail() 的情况下尝试它,因为您的表没有 ID。

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

    【讨论】:

    • 谢谢你这工作!
    • 很乐意提供帮助,如果解决了您的问题,请采纳答案
    • 我会在几秒钟内接受 现在不允许我
    • 谢谢,我会等
    【解决方案2】:

    client_has_orders 表没有名为 id 的列。该代码正在寻找一个 id 列来删除该行,但它不存在于表中。要解决此问题,您应该在 where 子句中将 id 更改为 order_id

    $clientOrder = clientHasOrder::where('order_id',$id)->firstOrFail();
    

    确保 client_has_orders 表中的外键 order_id 引用 orders 表中的主键

    【讨论】:

      猜你喜欢
      • 2018-11-20
      • 2012-06-16
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      • 2012-09-01
      • 2013-04-18
      相关资源
      最近更新 更多