Martin1182
2 months ago
431
9
Laravel

Cannot add foreign key constraint

Posted 2 months ago by Martin1182

Hi, Can anyone help me fix a migration bug?

public function up()
    {
        Schema::create('category_product', function (Blueprint $table) {
            $table->unsignedBigInteger('id', true);
            $table->integer('product_id')->unsigned()->nullable();
            $table->foreign('product_id')->references('id')
                ->on('products')->onDelete('cascade');
            $table->integer('category_id')->unsigned()->nullable();
            $table->foreign('category_id')->references('id')
                ->on('category')->onDelete('cascade');
            $table->timestamps();
        });
    }

Error

   Illuminate\Database\QueryException

  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `category_product` add constraint `category_product_product_id_foreign` foreign key (`product_id`) references `products` (`id`) on delete cascade)

  at D:\www\MAGZ-Ecommerce\vendor\laravel\framework\src\Illuminate\Database\Connection.php:671
    667|         // If an exception occurs when attempting to run a query, we'll format the error
    668|         // message to include the bindings with SQL, which will make this exception a
    669|         // lot more helpful to the developer instead of just the database's errors.
    670|         catch (Exception $e) {
  > 671|             throw new QueryException(
    672|                 $query, $this->prepareBindings($bindings), $e
    673|             );
    674|         }
    675|

  1   D:\www\MAGZ-Ecommerce\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOStatement.php:129
      Doctrine\DBAL\Driver\PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

  2   D:\www\MAGZ-Ecommerce\vendor\doctrine\dbal\lib\Doctrine\DBAL\Driver\PDOStatement.php:127
      PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint")

Thank you for all the help!

Please sign in or create an account to participate in this conversation.