【问题标题】:Laravel migration with foreign key drops 1064 error使用外键进行 Laravel 迁移会出现 1064 错误
【发布时间】:2014-11-03 17:04:58
【问题描述】:

我已经花了很多时间,但仍然无法使用外键更改进行迁移。我明白了

[Illuminate\Database\QueryException]                                                 
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your S  
  QL syntax; check the manual that corresponds to your MySQL server version for the r  
  ight syntax to use near '1' at line 1 (SQL: alter table `posts` add constraint post  
  s_author_foreign foreign key (`author`) references `users` (`id`) on delete 1)       

我尝试迁移的类看起来像

<?php

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

class CreatePostsTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        if (!Schema::hasTable('posts')) {
            Schema::create('posts', function($table) {

                $table->engine = 'InnoDB';

                $table->increments('id');
                $table->string('title', 255);
                $table->string('slug', 255);
                $table->unique('slug');
                $table->string('type', 255);
                $table->text('content');
                $table->integer('parent');
                $table->integer('author')->unsigned();
                $table->string('avatar', 255);
                $table->string('guid', 255);
                $table->string('mime_type', 255);
                $table->integer('menu_order');
                $table->boolean('status');
                $table->index('id');
                $table->timestamps();
            });

            Schema::table('posts', function($table) {
                $table->foreign('author')->references('id')->on('users')->onDelete();
            });

        }
    }

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

}

我的迁移出了什么问题?

【问题讨论】:

    标签: mysql laravel-4 syntax-error database-migration


    【解决方案1】:

    错误说明了一切。

    也许你想要这个:

    $table->foreign('author')->references('id')->on('users')->onDelete();
    

    成为:

    $table->foreign('author')->references('id')->on('users')->onDelete('cascade');
    

    或者简单地说:

    $table->foreign('author')->references('id')->on('users');
    

    查看文档here

    【讨论】:

      猜你喜欢
      • 2014-04-03
      • 2019-01-31
      • 2014-09-27
      • 2016-04-02
      • 2018-09-22
      • 2016-07-06
      • 2015-08-14
      • 2019-10-19
      • 2021-02-21
      相关资源
      最近更新 更多