【问题标题】:SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax, [duplicate]SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误,[重复]
【发布时间】:2022-01-11 21:37:32
【问题描述】:

我有这个带有 movie_idtable movies 和带有 actor_idtable 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 collat​​e 'utf8mb4_unicode_ci'' 附近使用正确的语法(SQL:创建表 movie_actor () 默认字符集 utf8mb4 collat​​e '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 该列包含外键或主键之前创建列来保存数据

标签: php sql laravel mariadb


【解决方案1】:

movie_actor 中没有定义任何列。

如果您想创建列然后设置为外键,请使用foreignId 而不是foreign,但请检查the docs 的语法是否正确,因为它不完全相同。在你的情况下:

     Schema::create('movie_actor', function (Blueprint $table) {
            $table->foreignId('actor_id')->constrained();
            $table->foreignId('movie_id')->constrained();
            $table->primary(['actor_id','movie_id']);
        });

假设您遵循约定,这应该会自动确定正确的表和 ID 名称。

注意:您可以使用constrained('table_name', 'primary_key_name') 准确指定表和主键名称。

【讨论】:

  • 问题表明他们没有遵循命名约定; movies 表有movie_id 列作为PK。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-02
  • 2019-08-08
  • 1970-01-01
  • 2011-05-31
  • 2020-05-03
  • 2020-02-15
相关资源
最近更新 更多