Migrate with foreign key

Hy guys.

I have tryed run a migrate with addForeignKey(), but it don’t run. I don’t know if understood the manual, or, if it’s not so clear.


$this->createTable('posts', [

            'id' => $this->primaryKey(),

            'id_autor' => addForeignKey('fk_autor', 'posts', 'id_autor', 'usuarios', 'id'),

            'id_categoria' => addForeignKey('fk_categoria', 'posts', 'id_categoria', 'categorias', 'id'),

            'titulo' => $this->string(200)->notNull(),

            'noticia' => $this->text()->notNull(),

            'tags' => $this->string(250),

            'status' => $this->smallInteger()->notNull()->defaultValue(1),

            'visualizacoes' => $this->smallInteger()->defaultValue(0),

            'created_at' => $this->datetime()->notNull(),

            'updated_at' => $this->datetime()->notNull(),

        ]);

OBS I heave already the table ‘usuarios’ and ‘categorias’ created.

Call addForeignKey() after you’ve created the table.


$this->createTable('posts', [

            'id' => $this->primaryKey(),

            'id_autor' => $this->integer()->notNull(),

            'id_categoria' => $this->integer()->notNull(),

            'titulo' => $this->string(200)->notNull(),

            'noticia' => $this->text()->notNull(),

            'tags' => $this->string(250),

            'status' => $this->smallInteger()->notNull()->defaultValue(1),

            'visualizacoes' => $this->smallInteger()->defaultValue(0),

            'created_at' => $this->datetime()->notNull(),

            'updated_at' => $this->datetime()->notNull(),

        ]);

$this->addForeignKey('fk_posts_autor', 'posts', 'id_autor', 'usuarios', 'id');

$this->addForeignKey('fk_posts_categoria', 'posts', 'id_categoria', 'categorias', 'id');



And, I guess the names of the constraint should be unique in the database.

Thanks @softark