0

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
whoi
  • 3,281
  • 7
  • 36
  • 44
  • I found 'Describe tablename' which contains meta info about which columns are references to other tables but is not enough to determine relations.. – whoi Oct 21 '09 at 23:17

2 Answers2

2

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
  • 3,281
  • 7
  • 36
  • 44
0

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
  • 52,691
  • 28
  • 123
  • 168
  • 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 Oct 22 '09 at 00:06