[英]getting 'SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint' error with migration
[英]Problem SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
我正在嘗試在 Laravel 中創建外鍵但是當我使用 artisan 遷移我的表時,我拋出了以下錯誤:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `products` add constraint `products_user_id_foreign` foreign key (`user_id`) references `users` (`id`))
這是我的用戶遷移
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('surname')->nullable();
$table->string('showname')->nullable();
$table->string('business')->nullable();
$table->string('NIP')->nullable();
$table->string('PESEL')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('postalcode')->nullable();
$table->string('phone')->nullable();
$table->string('comments')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
這是我的產品遷移
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('detail')->nullable();
$table->integer('user_id')->nullable();
$table->string('category')->nullable();
$table->date('launchdate')->nullable();
$table->date('expirationdate')->nullable();
$table->integer('billingperiod')->nullable();
$table->integer('renewalprice')->nullable();
$table->integer('internalcost')->nullable();
$table->string('status')->nullable();
$table->timestamps();
});
Schema::table('products', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
請幫我。 我不知道該怎么辦。 我在databaase.php中將數據庫引擎更改為Inno DB,但它根本沒有幫助。
Laravel 的increments()
創建了一個“自動遞增 UNSIGNED INTEGER(主鍵)等效列。 ”。 您的外鍵列user_id
必須與它所引用的列的類型完全相同。
在您的CreateProductsTable
遷移中,更改
$table->integer('user_id')->nullable();
至
$table->integer('user_id')->unsigned()->nullable();
然后再試一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.