Welcome Guest, Not a member yet? Register   Sign In
CodeIgniter Database Helper to Add and Drop Foreign Keys
#1

CodeIgniter Database Helper to Add and Drop Foreign Keys
https://gist.github.com/natanfelles/4024...9d82dec281

PHP Code:
<?php
/**
 * @author   Natan Felles <[email protected]>
 */
defined('BASEPATH') OR exit('No direct script access allowed');
if ( ! 
function_exists('add_foreign_key'))
{
    
/**
     * @param string $table
     * @param string $foreign_key
     * @param string $references
     * @param string $on_delete
     * @param string $on_update
     *
     * @return string SQL command
     */
    
function add_foreign_key($table$foreign_key$references$on_delete 'RESTRICT'$on_update 'RESTRICT')
    {
        
$constraint "{$table}_{$foreign_key}_fk";
        
$sql "ALTER TABLE {$table} ADD CONSTRAINT {$constraint} FOREIGN KEY ({$foreign_key}) REFERENCES {$references} ON DELETE {$on_delete} ON UPDATE {$on_update}";
        return 
$sql;
    }
}
if ( ! 
function_exists('drop_foreign_key'))
{
    
/**
     * @param string $table
     * @param string $foreign_key
     *
     * @return string SQL command
     */
    
function drop_foreign_key($table$foreign_key)
    {
        
$constraint "{$table}_{$foreign_key}_fk";
        
$sql "ALTER TABLE {$table} DROP FOREIGN KEY {$constraint}";
        return 
$sql;
    }


Must be used in a query, like:
PHP Code:
$fields = array(
    
'id'         => [
        
'type'           => 'INT(11)',
        
'auto_increment' => TRUE,
    ],
    
'user_id'    => [
        
'type'     => 'INT(11)',
    ],
);
$this->dbforge->add_field($fields);
$this->dbforge->add_key('id'TRUE);
$this->dbforge->create_table($this->table);
$this->db->query(add_foreign_key($this->table'user_id''users(id)''CASCADE''CASCADE')); 
and
PHP Code:
$this->db->query(drop_foreign_key($this->table'user_id'));
$this->dbforge->drop_table($this->table); 
Reply




Theme © iAndrew 2016 - Forum software by © MyBB