【问题标题】:Laravel change `id` to `AUTO_INCREMENT`Laravel 将 `id` 更改为 `AUTO_INCREMENT`
【发布时间】:2019-11-15 05:49:24
【问题描述】:

我有一个persons 表和blogs 表。 我想将persons 表的id 列更改为AUTO_INCREMENT

但它会引发错误。

人员表

id - integer (not auto_increment)
name - string

博客表

id - integer (auto_increment)
title - string
description - text
created_by - integer (foreign key) 

我创建了一个迁移来更改 idpersons 表。

更改用户迁移

Schema::table('persons', function (Blueprint $table) {
            $table->bigIncrements('id')->change();
        });

我抛出一个错误

  Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1833 Cannot change column 'id': used in a foreign key constraint 'blogs_created_by_foreign' of table 'db.blogs' (SQL: ALTER TABLE persons CHANGE id id BIGINT UNSIGNED AUTO_INCREMENT NOT NULL)

当我尝试这种方式时。

    public function up()
    {
        \DB::statement("LOCK TABLES  blogs WRITE, persons WRITE;");
        \DB::statement("ALTER TABLE blogs DROP FOREIGN KEY created_by, MODIFY id INT UNSIGNED;");
        \DB::statement("ALTER TABLE persons MODIFY id INT UNSIGNED AUTO_INCREMENT;");
        \DB::statement("ALTER TABLE blogs ADD CONSTRAINT created_by FOREIGN KEY (id) REFERENCES persons (id); UNLOCK TABLES;");

    }

错误:

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. (SQL: LOCK TABLES  blogs WRITE, persons WRITE;)

【问题讨论】:

标签: php mysql sql laravel laravel-5


【解决方案1】:

禁用外键检查然后启用它

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        Schema::table('persons', function (Blueprint $table) {
            $table->bigIncrements('id')->change();
        });
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

【讨论】:

  • 我想把id列改成递增,但问题是foreign key constraintblogs表中
  • 我将 bigIncrements 更改为 increments 并且它有效。谢谢兄弟。
猜你喜欢
  • 2011-01-18
  • 2011-01-11
  • 2016-04-12
  • 2010-12-13
  • 2020-07-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
  • 2011-02-11
相关资源
最近更新 更多