Skip to content

Instantly share code, notes, and snippets.

@iNecas
Created February 10, 2011 22:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iNecas/821510 to your computer and use it in GitHub Desktop.
Save iNecas/821510 to your computer and use it in GitHub Desktop.
Convention foreign keys: plugin for Adminer (http://www.adminer.org)
<?php
/** Convention foreign keys: plugin for Adminer
* Links for foreign keys by convention user_id => users.id. Useful for Ruby On Rails like standard schema conventions.
* @author Ivan Nečas, @inecas
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other)
*/
class ConventionForeignKeys {
function foreignKeys($table) {
$ret = array();
foreach(fields($table) as $field => $args){
if(ereg("^(.*)_id$", $field, $args)){
$ret[] = array("table" => $args[1]."s", "source" => array($field), "target" => array("id"));
}
}
return $ret;
}
}
?>
@alixaxel
Copy link

ereg() is deprecated as of PHP 5.3, this should be equivalent:

if(preg_match('~^(.*)_id$~', $field, $args)){

@dkuk
Copy link

dkuk commented Sep 11, 2013

Added check for missed associations.
Missed links are blocks foreign tables on the scheme. Only links to present tables will be drawn

<?php

/** Convention foreign keys: plugin for Adminer
* Links for foreign keys by convention user_id => users.id. Useful for Ruby On Rails like standard schema conventions.
* @author Ivan Necas, @inecas
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other)
*/
class ConventionForeignKeys {
    static $table_names;

    function foreignKeys($table) {
        $ret = array();
        if(self::$table_names == NULL){
            self::$table_names = array();
            foreach(tables_list() as $tbl_syn => $tp) {
                self::$table_names[] = str_replace("`","", $tbl_syn);
            }
        }

        foreach(fields($table) as $field => $args){
            if(ereg("^(.*)_id$", $field, $args) && in_array($args[1]."s", self::$table_names)){
                $ret[] = array("table" => $args[1]."s", "source" => array($field), "target" => array("id"));
            }
        }
        return $ret;
    }
}

?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment