U
U
Uglik2016-05-08 22:35:43
Laravel
Uglik, 2016-05-08 22:35:43

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');
        });

I'm trying to link the users table with countries and keep the Foreign key for the country_id field:
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();
        });

I'm trying to migrate and I'm getting this error
[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

1 answer(s)
V
Vadimjke, 2022-01-25
@Vadimjke

$table->string('country_id')->index();
replace with:
$table->unsignedInteger('country_id')->index();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question