如何在laravel 5中删除父记录时不删除子记录?

时间:2016-01-18 07:26:53

标签: php laravel-5

我有一张有儿童记录的记录。现在,当我尝试删除该记录时,它应该说"您无法删除此记录;因为它有一个子记录"。怎么做才是laravel 5 ??

例如: 设备记录有一个部门列,当我尝试删除此设备记录时,它应该给出一条消息,"此记录有一个部门。你无法删除它"。

这是我的迁移脚本:

public function up()
{
Schema::create('equipment', function(Blueprint $table){
$table->string('id', 32)->unique()->index();
$table->string('equipment_no',32);
$table->string('organization_id',32)->index();
$table->foreign('organization_id')->references('id')->on('organization')->onDelete('cascade')->onUpdate('cascade');
$table->string('customer_id',32)->index();
$table->foreign('customer_id')->references('id')->on('customer')->onDelete('cascade')->onUpdate('cascade');
$table->string('equipment_type',32);
$table->string('equipment_category_id',32)->index();
$table->foreign('equipment_category_id')->references('id')->on('equipment_category')->onDelete('cascade')->onUpdate('cascade');
$table->string('equipment_model_id',32)->index();
$table->foreign('equipment_model_id')->references('id')->on('equipment_model')->onDelete('cascade')->onUpdate('cascade');
$table->string('equipment_fabricat_id',32)->index();
$table->foreign('equipment_fabricat_id')->references('id')->on('equipment_fabricat')->onDelete('cascade')->onUpdate('cascade');
$table->string('department_id',32)->index();
$table->foreign('department_id')->references('id')->on('department')->onDelete('cascade')->onUpdate('cascade');
$table->text('location');
$table->string('inspection_interval',45);
$table->foreign('added_by')->references('id')->on('user')->onDelete('cascade')->onUpdate('cascade');
$table->SoftDeletes();
$table->timestamps();
});
}

我在控制器页面上的销毁功能是:

public function destroy($id)
{
$equipment = Equipment::findOrFail($id);
$equipment->delete();
return Redirect::route($this->route)->with($this->success, trans($this->deletemsg));
}

任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:0)

这是正确的方法: - )

这是因为存在关系(外键)。通过删除您的父记录,您的子记录是“僵尸”(它们是浮动的)。

如果您仍想这样做:

  • 删除外键
  • 将存储引擎更改为MyISAM(如果您使用的是MySQL数据库)

另一种方法是删除子记录。示例表:

CREATE TABLE rooms (
    room_no int(11) NOT NULL AUTO_INCREMENT,
    room_name varchar(255) NOT NULL,
    building_no int(11) NOT NULL,
    PRIMARY KEY (room_no),
    KEY building_no (building_no),
    CONSTRAINT rooms_ibfk_1 
    FOREIGN KEY (building_no) 
    REFERENCES buildings (building_no) 
    ON DELETE CASCADE
) ENGINE=InnoDB;