Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create foreign key in Wordpress database?

I'm trying to make 3 database tables in Wordpress

1 of them I want to have relations from the other..but I cant find how to make reference keys and stuff in wordpress.

With this code I create on table.. but how to make references and keys cause 1 table will contain the relation between two tables.

    global $wpdb;

    $table_name = $wpdb -> prefix . "Person";

    if($wpdb ->get_var("SHOW TABELS LIKE '$table_name'") != $table_name)
    {
        $sql = "CREATE TABLE " . $table_name . " (
        `id` INTEGER(9) NOT NULL AUTO_INCREMENT,
        `titel` varchar(255) NOT NULL,
        `content` text NOT NULL,
         UNIQUE KEY id (id)
         );";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);

        add_option('createTBL_version', '1.0'); 
    }
like image 508
user3510507 Avatar asked Feb 18 '15 13:02

user3510507


1 Answers

Foreign keys work like this:

FOREIGN KEY(table_field_name) REFERENCES [table_to_be_referred](referred_field)

The field must exist in the referring table and must match exactly the definition of the referrer. Usually only primary keys are referred, due to their uniqueness.

Here's an example:

CREATE TABLE A (
    id INT NOT NULL PRIMARY KEY,
    name VARCHAR(10)
);

CREATE TABLE B (
    idB INT NOT NULL PRIMARY KEY,
    idA INT NOT NULL,
    name VARCHAR(10),
    FOREIGN KEY (idA) REFERENCES A(id)
);
like image 140
Phate01 Avatar answered Oct 13 '22 04:10

Phate01