【问题标题】:I can't do a foreign key, constraint error我不能做外键,约束错误
【发布时间】:2016-05-13 10:51:49
【问题描述】:

我遇到了一个通信错误,我无法解决它,知道 [Illuminate\Database\QueryException] SQLSTATE[42000] 这是完整的错误:

[Illuminate\Database\QueryException] SQLSTATE[42000]:语法错误 或访问冲突:1064 您的 SQL 语法有错误;查看 与您的 MySQL 服务器版本相对应的手册 在第 1 行的“无符号空”附近使用正确的语法(SQL:alter 表files 添加slug varchar(255) 无符号空)

一个单独的错误:

[PDOException] SQLSTATE[42000]:语法错误或访问冲突: 1064 您的 SQL 语法有错误;检查手册 对应于您的 MySQL 服务器版本,以便使用正确的语法 第 1 行的“无符号空值”附近

他是我试图做外键的表:

文件

  public function up()
    {
        Schema::create('files', function($table)
        {
            $table->engine = 'InnoDB';
            $table->increments('id')->unsigned();
            $table->string('name')->nullable();
            $table->boolean('enable_sch')->nullable();
            $table->datetime('schdate')->nullable();
            $table->string('flsize')->nullable();
            $table->timestamps();
        });
        Schema::table('files', function($table)
        {
          $table->string('slug')->unsigned()->nullable();
          $table->foreign('slug')->references('slug')->on('slugs');
        });
    }

蛞蝓

public function up()
    {
        Schema::create('slugs', function($table)
        {
            $table->engine = 'InnoDB';
            $table->string('nameslug');
            $table->string('slug')->unsigned()->nullable();
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('slugs');
    }

我想要做的是将slugs table 中的*slug column* 添加到files table

【问题讨论】:

    标签: php mysql database laravel octobercms


    【解决方案1】:

    我猜string 数据类型不能是unsigned(),这就是您收到错误的原因。

    在两个迁移中都使用这个:

    $table->string('slug')->nullable();
    

    【讨论】:

    • Mhhh 我将其更改为 $table->integer('slug')->nullable(); 我正在消失的错误,但我还有另一个 [Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1005 Can't create table 'october.#sql-3f9_3b' (errno: 150) (SQL: alter tab le `files` add constraint files_slug_foreign forei gn key (`slug`) references `slugs` (`slug`))
    • 尝试分离迁移。暂时从目录中删除files迁移并运行php artisan migrate命令。然后将该迁移移回并再次运行该命令。
    • 尝试将$table->string('slug')->nullable(); 移至Schema::create 子句。然后将Schema::table 部分放在您要向表中添加外键的位置到单独的迁移文件中。运行将创建表的迁移,然后运行将添加外键的迁移。有时它对我有用。
    • 这行得通,但是当我尝试建立关系时出现问题,但我不知道是什么......
    • 我不知道我是否可以与string 建立这些关系,这可能是问题所在。
    【解决方案2】:

    当我在 Laravel 中使用 OctoberCMS 时,**models** file 上有 relationships 之类的 $hasMany$belongsTo

    如果在 OctoberCMS 上遇到问题,请咨询this

    【讨论】:

    • 请避免仅链接回答,而是引用对您来说是解决方案的相关部分。
    猜你喜欢
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2018-09-15
    • 2023-03-13
    • 2015-04-03
    相关资源
    最近更新 更多