简体   繁体   中英

how can I make restrictions if I want to delete a data in the database and it is foreign key in codeigniter?

I have two tables named "location" which consist of "location_id" and "location_name" and the other table is "computer" which have the "location" as a foreign key. Now whenever I want to delete a data which is used in the table "computer" I got an error message:

A Database Error Occurred Error Number: 1451

Cannot delete or update a parent row: a foreign key constraint fails ( cmms . computer , CONSTRAINT computer_ibfk_1 FOREIGN KEY ( location ) REFERENCES location ( location_id ))

DELETE FROM location WHERE location_id = '30'

Filename: C:/xampp/htdocs/cmms/application/models/asset_model.php

Line Number: 9

How can I check if it exist in table "computer" there will be a message and if it doesn't exist it will automatically delete the data in "location" table?

my code in my controller which is asset_management.php is:

public function deleteloc(){
  $this->load->model("asset_model");
  $u = $this->uri->segment(3);
  $this->asset_model->deletelocation($u);
  redirect('asset_management/locations');         
}

My code in my model which is asset_model is:

public function deletelocation($a){
    $this->db->delete('location', array('location_id' => $a));
    return;
}

please help. THANK YOU SO MUCH!!

You need to remove a value from the computer table before being able to remove this row. There is a row in the computer table depending on this row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM