David
David

Reputation: 447

foreign key not created with laravel migration

I would like to add a foreign key into the users tables :

a user has a town (ville in french) and a town can have many users :

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('adresse');

        //un user à une seule ville
        //une ville peut avoir plusieurs users
        $table->unsignedBigInteger('villes');

        $table->foreign('villes_id')->references('id')->on('villes');
        ...


        $table->timestamps();
    });
}

my villes (town) migration

public function up()
{
    Schema::create('villes', function (Blueprint $table) {
        $table->id();
        $table->string('nom',100);
        $table->integer('cp');
        $table->string('pays',50);
        $table->timestamps();
    });
}

I renamed the migrations (I don't know if it's good to do that ?) and this is order of my migrations, like you can see, I creat villes before users :

enter image description here

I've got this error in the terminal :

Illuminate\Database\QueryException

SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'villes_id' doesn't exist in table (SQL: alter table users add constraint users_villes_id_foreign foreign key (villes_id) references villes (id))

Upvotes: 0

Views: 1110

Answers (1)

Robert Kujawa
Robert Kujawa

Reputation: 997

It's not working because your setting your foreign key on a column that doesn't exist. The column name is villes but your setting foreign key on villes_id.

Change the column name like this:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('adresse');

    $table->unsignedBigInteger('villes_id');
    $table->foreign('villes_id')->references('id')->on('villes');
    // ...

    $table->timestamps();
});

Upvotes: 1

Related Questions