0

I am trying to reference the 'title' column of questions_solutions_language table to the 'title' column of questions table but i am not able to do so

My questions_solutions_language migration

public function up()
    {
        Schema::create('questions_solutions_language', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('language');
            $table->text('solution');
            $table->timestamps();
        });

        Schema::table('questions_solutions_language', function($table)
        {
            $table->foreign('title')
            ->references('title')->on('questions')
            ->onDelete('cascade');
        });
    }

My Questions migration:

  $table->id();
            $table->string('title');
            $table->string('url');
            $table->string('category');
            $table->string('difficulty');
            $table->string('languages')->nullable(true);
            $table->timestamps();

I tried referencing the id column of questions_solutions_language to the id column of questions and it works fine. But as soon as i try to reference the string column i get error. I also tried doing the migrations separately still it doesnt work. Any help will be greatly appreciated

  • it is because foreign id columns in laravel are supposed to be unsigned big integer, since id column is unsignedbigint then it works. I'd also suggest use $table->foreignIdFor('table') instead of doing this manually. – Sumit kumar Feb 20 '23 at 13:56
  • Thank you for your response. Is there no way to set strings as foreign key then? –  Feb 20 '23 at 13:57
  • no that's not how mysql foreign keys are supposed to work you can use ID's for it and work with it. – Sumit kumar Feb 20 '23 at 14:01
  • As long I know foreign keys are based in primary keys. Maybe this explanation gives you more details https://stackoverflow.com/questions/4813727/is-string-or-int-preferred-for-foreign-keys – Farid Feb 20 '23 at 14:05
  • So are you saying i should set my primary key to string column and then try again? –  Feb 20 '23 at 14:10
  • yes if you make title primary and remove $table->id() in question can work but keep in mind storing same strings on 2 tables is not a good practice and bad for db normalization (3NF) ie "3NF is used to reduce the data duplication." for reference: https://stackoverflow.com/questions/723998/what-are-database-normal-forms-and-can-you-give-examples – Sumit kumar Feb 20 '23 at 14:21
  • Ohk thanks will check soon –  Feb 20 '23 at 18:45

1 Answers1

0

You can use string column as foreign key, but your questions.title column should have unique index.

katsarov
  • 1,732
  • 2
  • 12
  • 16