bastinald / laravel-automatic-migrations

Automatic Laravel model migrations.
42 stars 11 forks source link

Pivot Tables #7

Open MACscr opened 2 years ago

MACscr commented 2 years ago

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 commented 2 years ago

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

heyjoe1984 commented 2 years ago

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