laravel - 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 的数据,如何显示一条消息显示该行不允许删除?
解决方案
如果您使用的是外键并且它不是“级联”删除,那么当在某处使用相同的 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
假设,如果您正在使用级联删除,并且您试图删除项目表中使用的类别,这将删除项目表中的类别和相关项目列表。
如果您使用非级联方法,则在项目表中使用该类别时将不允许您删除该类别。
推荐阅读
- java - IntelliJ - 无法解析符号“数组”
- xilinx - vhdl 延迟线实现属性
- python - 我对这段代码使用套接字接收多播的结论是否合理?
- c - STM32H7 SPI时钟频率,不随不同的BaudratePrescaler值变化
- php - 如何在 span 标签中添加 css 类作为回报
- javascript - Eslint 警告不允许我推动回购
- mysql - 我想在 mysql 中使用 join in codeigniter 来分隔值
- spring - 在 spring + hibernate 中保存 creationTimestamp 和 updatedTime
- python - 从源代码构建时,如何在 Colab 中永久安装诸如 opencv 之类的库?
- javascript - 在 VSCode 中,JSHint 警告缺少分号