亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

刪除時的 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 關注
  • 92 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號