Search code examples
phplaraveltransitive-closure-table

Can't migrate in Laravel4 using ClosureTable


I'm using ClosureTable for Laravel. and i am having a problem with migrating.

This is what my migration script looks like:

//Page_Closure migration script

public function up()
{
    Schema::table('page_closure', function(Blueprint $table)
    {
        $table->engine = 'InnoDB';

        Schema::create('page_closure', function(Blueprint $t)
        {
            $t->increments('ctid');

            $t->integer('ancestor', false, true);
            $t->integer('descendant', false, true);
            $t->integer('depth', false, true);
              //problem after this line.
            $t->foreign('ancestor')->references('id')->on('pages');
            $t->foreign('descendant')->references('id')->on('pages');
        });
    });
}

An error occurs when the foreign key is created. IDK why, but based on my my migration queue "page closure" runs first before the "page" script.

 [Illuminate\Database\QueryException]                                                                                                              
  SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'page_closure' already exists (SQL: create table `page_closure` (`ctid` int unsign  
  ed not null auto_increment primary key, `ancestor` int unsigned not null, `descendant` int unsigned not null, `depth` int unsigned not null) defa  
  ult character set utf8 collate utf8_unicode_ci)  

Solution

  • By doing Schema::table('page_closure', ...) then Schema::create('page_closure', ...) inside it. You are basically telling Laravel to find an existing table called page_closure, then create a table with the same name. That's why you are getting "Table 'page_closure' already exists" error.

    You don't need the Schema::table() part. Just put your $table->engine = 'InnoDB' in your Schema::create() like this...

    public function up()
    {
        Schema::create('page_closure', function(Blueprint $t)
        {
            $table->engine = 'InnoDB';
    
            $t->increments('ctid');
            // ... the rest of the columns
        }
    }
    

    It seems like your table has already been created too but the migration was not completed. So your migration table is probably corrupt. You will need to drop the table manually and run the migration again.