【问题标题】:laravel relationship on deletelaravel 删除关系
【发布时间】:2020-08-02 08:02:02
【问题描述】:

我正在编写具有三个表的 laravel 应用程序

  1. 类别
  2. 公司
  3. 优惠券

并且 coupons 有 category_id , company_id for relationship 事情是当我删除我想在优惠券表中设置的类别 category_id 为 null 而不是因为离开而将其留在那里它会导致问题我看到了外键和 onDelete 但我似乎无法理解它我将分享迁移和删除方法

优惠券迁移

 $table->id();
        $table->string('title');
        $table->string('link');
        $table->longText('terms');
        $table->string('show_image');
        $table->string('coupon_code');
        $table->tinyinteger('special');
        $table->integer('category_id');
        $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');;
        $table->integer('company_id');
        $table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');;
        $table->timestamps();

关于其他表格,他们只有 title , image , id 所以不需要分享它们

分类删除功能

public function destroy(Request $request , $id)
{
    $destroy_category = Categories::find($id);
    //delete the icon
    $icon = $destroy_category->icon;
    File::delete(public_path($icon));
    $destroy_category->delete();
    return redirect('/category/index')->with('success' , 'Category Deleted Successfully');
}

请告诉我应该如何将 category_id 设置为 null 或对其进行处理

提前致谢

【问题讨论】:

  • 使用这种类型的逻辑,您可能希望查看 deletingdeleted 事件的模型观察者,并使用它来取消相关优惠券上您想要的字段。跨度>

标签: php laravel relationship


【解决方案1】:

执行以下操作:

  • php artisan make:observer CategoryObserver
  • 打开app/Observers/CategoryObserver.php
  • deleting() 方法中,输入:
    //delete the icon
    $icon = $destroy_category->icon;
    File::delete(public_path($icon));
    $destroy_category->delete();
  • 打开app/Provivers/AppServiceProvider.php并将其放入boot()方法中:
Category::observe(CategoryObserver::class); //import the class correctly
  • 将您的控制器代码更改为:
public function destroy(Request $request , $id)
{
    $destroy_category = Categories::find($id);
    $destroy_category->delete(); //this will fire the CategoryObserver::deleting() method

    return redirect('/category/index')->with('success' , 'Category Deleted Successfully');
}

【讨论】:

  • 我会尝试的,但我可以请你解释一下,我的意思是这个 opserver 是做什么的
  • 在 Laravel 上下文中,它用于监听模型上的 CRUD 操作。例如,如果您的应用程序需要在每次创建模型对象时执行某些操作,而不是在各个地方编写逻辑,您可以设置一个监听“创建”操作的观察,这样每当模型创建时都会调用该方法.也许你可以在这里阅读dev.to/hsmobio/what-is-laravel-model-observers-4723
  • 如果8n数据库端可以解决,为什么还要使用观察者?
  • 当类别被删除时,他正在尝试删除文件File::delete(public_path($icon));
  • NOO 你误会了我,我想要的是当我删除类别时,我的优惠券表中的类别 ID 应设置为空;这就是我想要的,因为如果它不为空,则从 db 检索记录时会出现问题,并且基于 djunehor 提供的代码不适合这种情况
猜你喜欢
  • 2015-05-15
  • 2016-01-02
  • 2018-11-03
  • 2015-05-14
  • 2020-12-14
  • 1970-01-01
  • 2018-05-19
  • 2016-04-02
  • 1970-01-01
相关资源
最近更新 更多