0

I am new at Laravel and I have a primary key field which is string because the project i am working on right now which requires underscore (_). Like this: 0001_0001. Since the primary key is string i also have to set foreign key as string. So, I want to know is there any way to set string as foreign key. I am using mysql database as the database.

Srijan Karki
  • 1,576
  • 2
  • 14
  • 21

2 Answers2

0

The declaration will same for the int or string

Schema::table('priorities', function($table) {
       $table->foreign('user_id')->references('id')->on('users');
   });

But the performance will be differ please check the answer for more info.

Community
  • 1
  • 1
vijaykumar
  • 4,658
  • 6
  • 37
  • 54
  • yup that is true. but what i want is to set the reference on string i.e. not on `id` but on `unique_id` which is `string` and `unique` but not primary key – Srijan Karki May 10 '16 at 04:56
  • I think it's not a problem are you getting any error when you use strings? – vijaykumar May 10 '16 at 05:16
  • yes, i do get error. `1215 error: Cannot add foreign key constraint unique_id`. This error is thrown because unique_id is string in another table – Srijan Karki May 10 '16 at 05:21
  • Are you sure you are using same datatypes in both tables? Please check this http://stackoverflow.com/questions/16969060/mysql-error-1215-cannot-add-foreign-key-constraint – vijaykumar May 10 '16 at 05:25
0

try with $table->string('user_id')->unique(); it will help you and If you would like the relationship to use a value other than id, you may pass a third argument to the hasOne method specifying your custom key: Like this:

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');