【问题标题】:How to softDelete row in table that have foreign key constraint to another table ? (Laravel)如何软删除表中对另一个表有外键约束的行? (拉拉维尔)
【发布时间】:2022-11-12 16:20:51
【问题描述】:

我有表订单,这是订单的迁移文件

<?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('orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->tinyInteger('status');
            $table->date('order_on');
            $table->unsignedBigInteger('shipping_id');
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('payment_id');
            $table->unsignedBigInteger('discount_id');
            $table->foreign('shipping_id')->references('id')->on('shippings');
            $table->foreign('user_id')->references('id')->on('users');
            $table->foreign('payment_id')->references('id')->on('payments');
            $table->foreign('discount_id')->references('id')->on('discounts');
            $table->unique(['user_id', 'discount_id', 'payment_id', 'shipping_id']);
            $table->softDeletes();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('orders');
    }
};

这是 DataGrip 中的订单表 所有这些行都是我立即添加的 并且有一个表 OrderDetail 具有外键 order_id 指的是 Order 表

我有 OrderController 有 CRUD 订单,但是当我想用这种方法软删除时:

public function destroy(Order $order) {
    DB::beginTransaction();
    try {
        $order->delete();
        return response(['message' => 'Order deleted successfully']);
    } catch (\Exception $e) {
        DB::rollback();
        return response(['error' => $e->getMessage()], 500);
    }
}

当我使用$order-&gt;delete();时出现错误

"error": "SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row

但我认为软删除只是更新 Order 表中的 deleted_at 列,而不影响 Order Detail 表。

【问题讨论】:

    标签: php laravel backend


    【解决方案1】:

    如果要删除父记录,例如删除级联、设置 null 等,则子行有不同的规则。

    $table->foreign('shipping_id')->references('id')->on('shippings')->onDelete('cascade'); 
    

    如果您要删除父记录,onDelete('cascade') 也会删除子行。

    你可以阅读更多来自official docos

    【讨论】:

      猜你喜欢
      • 2021-08-22
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      相关资源
      最近更新 更多