I'm using laravel 5.5 and I have 2 columns coupons
and carts
in my carts table migrations I have coupon_code
which will get code from coupons
table and the result will be cutoff price from total price in cart.
This is my cart migration:
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('product_id')->unsigned();
$table->integer('coupon_code')->unsigned();
$table->timestamps();
});
Schema::table('carts', function($table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('product_id')->references('id')->on('products');
$table->foreign('coupon_code')->references('code')->on('coupons');
});
}
and I get this error when I try to run php artisan migrate
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `carts` add constraint `carts_coupon_code_foreign` foreign key (`coupon_co
de`) references `coupons` (`code`))
[PDOException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
How can I solve that?
Update
Coupon
migration
public function up()
{
Schema::create('coupons', function (Blueprint $table) {
$table->increments('id');
$table->string('code')->unique();
$table->decimal('amount');
$table->date('valid_from');
$table->date('valid_to');
$table->timestamps();
});
}
Idea!
What if I make coupon_code
string and nullable in my carts table and then make it scope to validate coupon code from coupons table then cutoff the price? do you think that will work? and if yes, is there someone to help me with that scope?