views:

191

answers:

2

Hi all;

I searched a lot but could not find a way to dump table relations like one-to-one, one-to-many vs in PHP.

Is there a way to handle this issue in PHP?

A result might be:

array(
   'tableA' => array(
                'one-to-one' => array('tableB', 'tableC'),
                'one-to-many' => array('tableD'),

   'tableB' => array(
                'one-to-one' => array('tableA')


    ...        
)

Any suggestions are much appreciated. Thanks.

A: 

You have to do this yourself by parsing the output of the DESCRIBE command. You might consider using a ORM like doctrine. You tell doctrine to make a one to one relation on table a and table b and it handles the rest.

Byron Whitlock
I use code igniter and Datamapper for ORM, and I am creating a simple CRUD generator which needs this relations. I found a tmp solution which is below answer
whoi
+1  A: 

I found a script at http://dev.mysql.com/doc/refman/5.0/en/show-table-status.html which describes parsing table info with regex. I had manipulated the code to work. here is the code.

<?php
$conn = mysql_connect('localhost', 'user', 'pass');
if (!$conn) {
    die('Could not connect: ' . mysql_error());
}

//DB connection already established
mysql_query("use db");
$res = mysql_query("SHOW CREATE TABLE tbl");
$row = mysql_fetch_assoc($res);
mysql_free_result($res);

//Only work on InnoDB foreign key info.
if(preg_match_all(
         '/FOREIGN KEY \(`(.*)`\) REFERENCES `(.*)` \(`(.*)`\)/',
         $row['Create Table'],
         $matchArr)) {
    print_r($matchArr); //which writes down the result

}


?>
whoi