-1

In my migration file , I am adding organization id to the user's table , i tried all of the code below but not solved yet

class AddOrganizationIdToUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
//            $table->foreignId('organization_id')->references('id')->on('organizations')->onDelete('cascade');
            $table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();
//            $table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
swatantra
  • 383
  • 1
  • 7
  • 18

3 Answers3

6

I have data on my user's table so it is giving errors while migrating, to solve it I add the field as nullable

$table->foreignId('organization_id')->nullable()->references('id')->on('organizations')->onDelete('cascade');
swatantra
  • 383
  • 1
  • 7
  • 18
0

if you write with foreignId need:

$table->foreignId('organization_id')->constrained('organizations')->cascadeOnDelete();

or just foreign

$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');
0

What could be the issue is that this migration is running before the organizations table migration, and when it tries to find it to create the constraint it fails.

What I would suggest is on the AddOrganizationIdToUsersTable :

Schema::table('users', function (Blueprint $table) {
            $table->foreignId('organization_id');
        });

And on the Organization creation migration:

Schema::table('users', function(Blueprint $table) {
            $table->foreign('organization_id')->references('id')->on('organizations');
        });

#2 solution: Move the migration of Organization table to run before your AddOrganizationIdToUsersTable by changing the timestamp on the name of the file

Marwane Ezzaze
  • 1,032
  • 5
  • 11