laravel - 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 表列“用户名”。两者都已经在字符串中。
解决方案
$table->string('created_by')->unsigned();
我认为问题在于 unsigned 仅用于数字而不是字符串删除 unsigned 并重试
推荐阅读
- reactjs - Redux 传奇。无法在 promise 'catch' 块中使用 yield
- nginx - 使用 Nginx 转发 Keberos 票证
- r - R:从 xts 对象导出特定值类
- javascript - Vue-tables-2 create .pdf (pdfmake) 'malformed table row' 错误
- postgresql - PostgreSQL 如何根据另一个表上的插入在一个表上的列上创建 AVG
- collections - 如何在 Waterline 独立中定义基本类型的集合?
- vba - VBA If/Else 语句根据列数复制和粘贴数据
- powershell - 在 foreach UNIQUE 中创建“cmd /c”命令
- android - 如何在不更新 APK 文件的情况下解决违反使用 Android 广告 ID 政策和第 4.8 节的问题
- command-line-interface - Express Gateway 命令行界面“例如”