首页 > 解决方案 > Laravel 迁移:无法将 FK 添加到两种字符串类型

问题描述

我正在尝试在 Laravel 中创建外键,但是当我使用 artisan 迁移我的表时,我抛出了以下错误:

Copy\vendor\laravel\framework\src\Illuminate\Database\Connection.php:465
      PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server 
version for the right syntax to use near 'unsigned not null, `updated_by` varchar(255) unsigned not null, `enabled` var...' at line 1")

课程迁移表:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateLessonTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('lesson', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->bigInteger('module_id')->unsigned();

            $table->text('content');

            $table->string('created_by')->unsigned();

            $table->string('updated_by')->unsigned();


            $table->string('enabled');
            $table->string('position');

            $table->timestamps();

        });

        Schema::table('lesson', function(Blueprint $table) {
            $table->foreign('module_id')->references('id')->on('modules');
            
            $table->foreign('created_by')->references('username')->on('admins');
            $table->foreign('updated_by')->references('username')->on('admins');
        });
                
    }

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

管理员迁移表:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAdminsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->id();
            $table->string('username');
            $table->string('password');
            $table->string('fname');
            $table->string('mname');
            $table->string('lname');
            $table->string('email');
            $table->timestamps();
        });
    }

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

我试图将课程表的 created_by 和 updated_by 列连接到 Admins 表列“用户名”。两者都已经在字符串中。

标签: laravel

解决方案


$table->string('created_by')->unsigned();

我认为问题在于 unsigned 仅用于数字而不是字符串删除 unsigned 并重试


推荐阅读