
create table cosito (
    id int primary key,
    enumer enum('uno','dos','tres') not null default 'uno',
    liga varchar(32) COLLATE latin1_spanish_ci NOT NULL,
    x int,
    KEY porfkliga(liga),
    CONSTRAINT elfk FOREIGN KEY (liga) REFERENCES vale(vale_id)
);

create table aba (
    id int primary key,
    enumer enum('uno','dos','tres') not null default 'uno',
    vale_number varchar(16) COLLATE latin1_spanish_ci NOT NULL,
    fecha date NOT NULL,
    KEY porfkliga(fecha, vale_number),
    CONSTRAINT valenumdated FOREIGN KEY (vale_number,fecha) REFERENCES vale(vale_number,fecha),
    x int,
    KEY porfx(liga),
    CONSTRAINT elx FOREIGN KEY (x) REFERENCES cisto(x)
);

SELECT table_name, referenced_table_name, CONSTRAINT_NAME, ORDINAL_POSITION, column_name, referenced_column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE table_schema = DATABASE() AND referenced_table_name IS NOT NULL
ORDER BY table_name, referenced_table_name, CONSTRAINT_NAME, ORDINAL_POSITION



    public function tablesRelation() {
        $tableRelation = [];
        $sql =
            "SELECT table_name, referenced_table_name, constraint_name, ordinal_position, column_name, referenced_column_name
            FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
            WHERE table_schema = DATABASE() AND referenced_table_name IS NOT NULL
            ORDER BY table_name, referenced_table_name, constraint_name, ordinal_position";
        foreach($this->db->selectArrayIndex($sql) as $r) {
            if(empty($tableRelation[$r['table_name']])) {
                $tableRelation[$r['table_name']] = ['references'=>[], 'referencedBy'=>[], 'orderby'=>1000];
            }
            if(empty($tableRelation[$r['referenced_table_name']])) {
                $tableRelation[$r['referenced_table_name']] = ['references'=>[], 'referencedBy'=>[], 'orderby'=>1000];
            }
            $tableRelation[$r['table_name']]['references'][] = [
                'tableReferences'=>$r['table_name'], 'colRefernces'=>$r['column_name'],
                'referencedTable'=>$r['referenced_table_name'], 'referencedColumn'=>$r['referenced_column_name']
            ];
            $tableRelation[$r['referenced_table_name']]['referencedBy'][] = [
                'referencedTable'=>$r['referenced_table_name'], 'referencedColumn'=>$r['referenced_column_name'],
                'tableReferences'=>$r['table_name'], 'colRefernces'=>$r['column_name']
            ];

        }
        return $this->foreignKeyOrder($tableRelation);
    }