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.

1
  • I found 'Describe tablename' which contains meta info about which columns are references to other tables but is not enough to determine relations.. Commented Oct 21, 2009 at 23:17

2 Answers 2

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

}


?> 
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.