【发布时间】:2020-08-02 08:02:02
【问题描述】:
我正在编写具有三个表的 laravel 应用程序
- 类别
- 公司
- 优惠券
并且 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 或对其进行处理
提前致谢
【问题讨论】:
-
使用这种类型的逻辑,您可能希望查看
deleting或deleted事件的模型观察者,并使用它来取消相关优惠券上您想要的字段。跨度>
标签: php laravel relationship