Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Try Vanilla Forums Cloud product

In this Discussion

How to add custom tables/columns in database via code?

I want to add some custom columns to database tables. So, when I will install or setup my application anywhere my custom tables/columns will automatically insert/update into the database. I want to implement this via code. Thanks in advance!

Comments

  • R_JR_J Cheerleader & Troubleshooter Munich Moderator

    This is easy, but you have to stick to some conventions to take benefit from all automatisms.

    If your plugin has a method called setup() it will be called automatically when the plugin is enabled. Therefore it is a good place to initiate the database change. But there is also another method with added functionality. If your plugin has a method called structure(), that method will be called everytime when the forum admin runs example.com/utility/structure, which might be needed if the databse got corrupted or during update processes.

    Therefore you should use both methods like that:

        public function setup() {
            $this->structure();
        }
    
        public function structure() {
            Gdn::structure()
                ->table('Comment')
                ->column('NewColumn', 'int', 0)
                ->set();
        }
    

    And in this example, you already see how to create a new row in table Comment. You can find more examples by looking at /applications/dashboard/settings/structrue.php and /applications/vanilla/settings/structrue.php
    An you should also take a look at /library/database/class.databasestructure.php and read the comments for e.g. its method column()

    Bleistivt
Sign In or Register to comment.