Reputation: 447
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 :
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 constraintusers_villes_id_foreign
foreign key (villes_id
) referencesvilles
(id
))
Upvotes: 0
Views: 1110
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