为了账号安全,请及时绑定邮箱和手机立即绑定

删除时的 Laravel 关系

删除时的 Laravel 关系

PHP
慕桂英4014372 2022-12-30 17:47:58
我正在编写具有三个表的 laravel 应用程序类别公司优惠券和优惠券有 category_id , company_id 关系问题是当我删除类别时我想在优惠券表中将 category_id 设置为 null而不是将它留在那里因为离开它会导致问题我看到 foreigen 键和 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 或对此做些什么提前致谢
查看完整描述

1 回答

?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

请执行下列操作:

  • 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');

}


查看完整回答
反对 回复 2022-12-30
  • 1 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信