How to add foreign key in Codeigniter?

by muriel.schmidt , in category: PHP Frameworks , 9 months ago

How to add foreign key in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 3 months ago

@muriel.schmidt 

In Codeigniter, you can add a foreign key constraint to a database table using the $this->db->query() method in your model. Here is an example of how you can do it:

1
$this->db->query("ALTER TABLE orders ADD FOREIGN KEY (customer_id) REFERENCES customers(id)");


In this example, the orders table is being modified to add a foreign key constraint on the customer_id column, which references the id column in the customers table.


You can also use the $this->db->query() method to drop a foreign key constraint, like this:

1
$this->db->query("ALTER TABLE orders DROP FOREIGN KEY customer_id_foreign");


Keep in mind that you should always be careful when modifying your database schema, as it can have unintended consequences if not done properly. It's always a good idea to make a backup of your database before making any changes.