Answer the question
In order to leave comments, you need to log in
Foreign key for string field in laravel?
Hello
Tell me if it is possible to use Foreign key for a field with type string
There is a table with a list of countries, I use string as a primary key:
Schema::create('countries', function (Blueprint $table) {
$table->string('id', 3)->unique()->index();
$table->string('name', 100);
$table->string('ru_name', 100);
$table->string('flag', 10)->unique();
$table->primary('id');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name', 40);
$table->string('last_name', 40);
$table->string('username', 40)->unique()->index();
$table->string('email')->unique();
$table->string('password');
$table->string('country_id')->index();
$table->foreign('country_id')->references('id')->on('countries');
$table->string('user_photo')->nullable();
$table->string('user_group')->index();
$table->rememberToken();
$table->timestamps();
});
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `users` add constraint `users_country_id_foreign` foreign key (`country_id`
) references `countries` (`id`))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question