I have two tables, a voucher and an order. The voucher needs to have a 16 character string as the ID, which is created randomly. Everything worked when the ID was incremented as an integer, but when changing to string, I just can't get it to add the foreign key, getting this error:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `orders` add constraint `orders_voucher_id_foreign` foreign k
ey (`voucher_id`) references `vouchers` (`id`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
And here are my tables:
Schema::create('vouchers', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->string('id');
$table->integer('value');
$table->string('status');
$table->timestamps();
});
Schema::create('orders', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('event_id')->unsigned();
$table->string('voucher_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('event_id')->references('id')->on('events');
$table->foreign('voucher_id')->references('id')->on('vouchers');
});
Any feedback would be really appreciated. Thanks in advance.
try with:
$table->string('id')->unique();