问题 SQLSTATE[HY000]:一般错误:1215 无法添加外键约束

我正在尝试在 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

     */

请帮我。我不知道该怎么办。我在databaase.php中将数据库引擎更改为Inno DB,但它根本没有帮助。


九州编程
浏览 169回答 1
1回答

一只甜甜圈

Laravelincrements()创建一个“自动递增 UNSIGNED INTEGER(主键)等效列。 ”。您的外键列user_id必须与其引用的列具有完全相同的类型。在您的CreateProductsTable迁移中,更改$table->integer('user_id')->nullable();到$table->integer('user_id')->unsigned()->nullable();然后再试一次。
打开App,查看更多内容
随时随地看视频慕课网APP