laravel-automatic-migrations icon indicating copy to clipboard operation
laravel-automatic-migrations copied to clipboard

Pivot Tables

Open MACscr opened this issue 3 years ago • 2 comments

Should i just create vanilla laravel migration tables for pivot tables or is there a way to handle it with this library? Lets say I have a Post model and a Category model and I want to be able to associate multiple Categories to a Post (belongsToMany).

MACscr avatar Nov 29 '21 18:11 MACscr

hmm, doesnt seem to handle foreign keys well. I ended up having a custom pivot table model for one of mine using:

    public function migration(Blueprint $table)
    {
        $table->unsignedBigInteger('bid_id')->index();
        $table->foreign('bid_id')->references('id')->on('bids')->onDelete('cascade');
        $table->unsignedBigInteger('user_id')->index();
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->primary(['bid_id', 'user_id']);
        $table->timestamps();
   }

and that ended working the first time, but if you run migrate:auto again when you make other new models/migrations, i ended up getting the following error:

SQLSTATE[23000]: Integrity constraint violation: 1022 Can't write; duplicate key in table '#sql-48d_8e8' (SQL: alter table `table_bid_bookmarks` add constraint `table_bid_bookmarks_bid_id_foreign` foreign key (`bid_id`) references `bids` (`id`) on delete cascade)

Here is a decent package for helping with creating some pivot table migration files though: https://github.com/laracasts/Laravel-5-Generators-Extended

MACscr avatar Dec 13 '21 21:12 MACscr

yeah its cause of the way it creates the indexes when creating the temporary table to diff with

best bet is to use traditional migration files for complex pivots like this

heyjoe1984 avatar Dec 19 '21 16:12 heyjoe1984