[英]Laravel change `id` to `AUTO_INCREMENT`
我有一个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)
我创建了一个迁移来更改persons
表的id
。
更改用户迁移
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;)
禁用外键检查然后启用它
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::table('persons', function (Blueprint $table) {
$table->bigIncrements('id')->change();
});
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.