Foreign Key

How do I create a column with foreign key?

Comments

  • R_JR_J Cheerleader & Troubleshooter Munich Moderator

    Vanilla doesn't use foreign keys, that might be the reason why foreign keys are not directly supported in the database classes. But you can always use raw SQL (if you know what you are doing 😀)


    $px = Gdn::structure()->databasePrefix();
    $queryString = "ALTER TABLE {$px}Comment ADD FOREIGN KEY (DiscussionID) REFERENCES {$px}Discussion(DiscussionID);";
    Gdn::sql()->query($queryString);
    


  • nithishnithish New
    edited October 2019

    $Structure = GDN::Structure();

    $Structure->table('FK_TEST')

    ->column('DiscussionID', 'int', false)

     ->set();

    $px = Gdn::structure()->databasePrefix();

    $queryString = "ALTER TABLE {$px}FK_TEST ADD  FOREIGN KEY (DiscussionID) REFERENCES {$px}Discussion(DiscussionID);";

    Gdn::sql()->query($queryString);


    @R_J I ran above queries but I keep getting => errno:150 "Foreign key constraint is incorrectly formatted"

  • R_JR_J Cheerleader & Troubleshooter Munich Moderator

    https://xrstf.de/2016/01/mysql-foreign-key-constraint-is-incorrectly-formed/


Sign In or Register to comment.