【发布时间】:2022-01-11 21:37:32
【问题描述】:
我有这个带有 movie_id 的 table movies 和带有 actor_id 的 table actor 都连接到 包含 actor_id PK FK 和 movie_id PK FK
的表 movie_actor当我尝试运行时,我在 Visual Studio Code 中收到此错误:php artisan migrate:fresh
SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的 ') 默认字符集 utf8mb4 collate 'utf8mb4_unicode_ci'' 附近使用正确的语法(SQL:创建表 movie_actor () 默认字符集 utf8mb4 collate 'utf8mb4_unicode_ci')
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateActorsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('actors', function (Blueprint $table) {
$table->id('actor_id');
$table->string('first_name',100);
$table->string('last_name',100);
});
Schema::create('movie_actor', function (Blueprint $table) {
$table->foreign('actor_id')->references('actor_id')->on('actors');
$table->foreign('movie_id')->references('movie_id')->on('movies');
$table->primary(['actor_id','movie_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('actors');
Schema::dropIfExists('movie_actor');
}
}
【问题讨论】:
-
您需要先创建列,然后才能在它们上创建外键。仅添加外键不足以在表中创建列。
-
除非我遗漏了一些 Laravel 魔法,否则您必须在通知 MySQL 该列包含外键或主键之前创建列来保存数据