Search code examples
phplaravelmigrationmany-to-manylaravel-artisan

How to: migration many-to-many laravel artisan


I am trying to find a way to migrate (and later on seed) a table generated by a many-to-many relation in laravel 5.2 (using artisan).

I have both my User.php and Role.php model here. Also the migration I tried for the many-to-many table. I can't work well with codeblocks here, so this is my code.

I get the error:

General error: 1005 Can't create table 'connect.#sql-2d0_2e' (errno: 150) (SQL: alter table 'users_has_roles' add constraint users_has_roles_usersid_foreign foreign key ('usersId') references 'users' ('id'))


Solution

  • Probably the problem is:

    $table->bigInteger('usersId')->unsigned();
    

    If you look into users table what type of column is for id. I think it is integer (unsigned) so it must be exact the same for column for which you create foreign key, so you should probably change above into:

    $table->integer('usersId')->unsigned();