首页 > 解决方案 > Laravel - 当存在依赖字段时如何防止行被删除

问题描述

我是一个laravel初学者。在我的 laravel CRUD 项目中,我有这些迁移表
GroupTable

class Group extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('group', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('group_code');
            $table->string('group_desc');
            $table->timestamps();
    });
}

类别表

class Category extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('category', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('category_code');
            $table->string('category_desc');
            $table->timestamps();
        });
    }

项目表

class Item extends Migration
{
   /**
    * Run the migrations.
    *
    * @return void
    */
     public function up()
   {
       Schema::create('item', function (Blueprint $table) {
           $table->bigIncrements('id');
           $table->string('item_code');
           $table->string('item_desc');
           $table->string('item_picture');
           $table->string('item_cost');
           $table->string('item_price');
           $table->string('group_desc');
           $table->string('category_desc');
           $table->timestamps();
       });

      
   }

ItemTable 中的 group_desc 和 category_desc 是 GroupTable 和 CategoryTable 的外键。

组控制器

 public function destroy($id)
    {
        Group::find($id)->delete();
        return response()->json(['success'=>'Group deleted successfully.']);
    }

类别控制器

public function destroy($id)
    {
        Category::find($id)->delete();
     
        return response()->json(['success'=>'Category deleted successfully.']);
    }

这是我对组的看法中的ajax删除功能

  //Delete
   $('body').on('click', '.deleteRecord', function () {
     
     var id = $(this).data("id");
     if(confirm("Are you sure want to delete? "))
   
    {
      $.ajax({
         type: "DELETE",
         url: "{{ url('group/delete') }}" + '/' + id,
         success: function (data) {
             table.draw();
         },
         error: function (data) {
             console.log('Error:', data);
         }
     });
    }
 });

在用户想要删除 GroupTable 或 CategoryTable 上的行之前,如果 ItemTable 有来自 GroupTable 或 CategoryTable 的数据,如何显示一条消息显示该行不允许删除?

标签: laravel

解决方案


如果您使用的是外键并且它不是“级联”删除,那么当在某处使用相同的 Id 时,laravel 将不允许您删除该行。例如,

$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); //inside item table. (CASCADE delete).


$table->foreign('category_id')->references('id')->on('categories');// non-cascade

假设,如果您正在使用级联删除,并且您试图删除项目表中使用的类别,这将删除项目表中的类别和相关项目列表。

如果您使用非级联方法,则在项目表中使用该类别时将不允许您删除该类别。


推荐阅读