2016-01-18 140 views
0

我有一个有儿童记录的记录。现在,当我尝试删除该记录时,应该说“您不能删除此记录;因为它有一个子记录”。如何做到这一点是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)); 
} 

谁能帮我一下吧?

+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;