首页 > 解决方案 > 无法在 Laravel 的表结构中设置外键

问题描述

我无法在 laravel 的表结构中设置外键。我已经尝试了这里提到的所有解决方案,但都没有奏效。

首先,我制作了一个名为“类别”的表

class CreateCategoriesTable extends Migration{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('nom');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('categories');
}

然后,我创建了另一个名为“exercices”的类 ,还没有外键

class CreateExercicesTable extends Migration{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('exercices', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('categorie_id')->unsigned();
        $table->string('nom');
        $table->string('description');
        $table->string('imageUrl');
        $table->timestamps();
        //$table->foreign('categorie_id')->references('id')->on('categories');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('exercices');
}

}

之后,我运行命令php artisan migrate:fresh从头开始​​创建表。一切运行良好。

Migrating: 2020_02_11_004702_create_categories_table
Migrated:  2020_02_11_004702_create_categories_table (0.06 seconds)
Migrating: 2020_02_11_005524_create_exercices_table
Migrated:  2020_02_11_005524_create_exercices_table (0.05 seconds)

但是现在,如果我删除“//$table->foreign('categorie_id')->references('id')->on('categories');”之前的双斜杠 然后运行“php artisan migrate”,我收到以下消息:“Nothing to migrate”。

之后,我尝试执行“php artisan migrate:fresh”以确保正确添加外键,但我收到此错误消息

    Illuminate\Database\QueryException  : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') default character set utf8mb4 collate 'utf8mb4_unicode_ci'' at line 1 (SQL: create table `exercices` () default character set utf8mb4 collate 'utf8mb4_unicode_ci')

  at /home/vagrant/code/project/vendor/laravel/framework/src/Illuminate/Database/Connection.php:669

任何帮助将不胜感激。谢谢!

标签: phpmysqllaravelkey

解决方案


推荐阅读