【发布时间】:2021-11-07 20:51:30
【问题描述】:
我在迁移表时遇到问题。
我有一个带有字符串 id 的 users 表,并且该表是之前使用 SQL 创建的,没有迁移。
后来,我创建了一个名为“调查”的表,该表具有 user_id 的外键,代码如下。
hema::create('surveys', function (Blueprint $table) {
$table->increments('id');
$table->string('user_id',40);
$table->foreign('user_id')->references('id')->on('users') ->onUpdate('cascade')->onDelete('cascade');
$table->string('gender');
$table->string('age');
$table->string('education');
$table->string('proficiency');
$table->string('behaviour');
$table->timestamps();
});
每当我尝试迁移它时,我总是收到以下错误,我不知道为什么会发生这种情况。 users 表中的 id 是 varchar 40,user_id 也是。
SQLSTATE[HY000]: General error: 1005 Can't create table `d0372341`.`surveys` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `surveys` add constraint `surveys_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade on update cascade)
at D:\xampp install\htdocs\game-db\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
688▕ // If an exception occurs when attempting to run a query, we'll format the error
689▕ // message to include the bindings with SQL, which will make this exception a
690▕ // lot more helpful to the developer instead of just the database's errors.
691▕ catch (Exception $e) {
➜ 692▕ throw new QueryException(
693▕ $query, $this->prepareBindings($bindings), $e
694▕ );
695▕ }
696▕ }
如果您能帮我解决这个问题,我将不胜感激。
【问题讨论】:
-
你能把你的 user 表的 schema 放进去吗?
-
创建表
users(idvarchar(40) NOT NULL,achievementstext DEFAULT NULL,levelint(11) NOT NULL DEFAULT 0,local_rankint(11) NOT NULL DEFAULT 0,moneyint(11) NOT NULL DEFAULT 0,slanttext DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4CREATE TABLEusers(idvar ) NOT NULL,achievementstext DEFAULT NULL,levelint(11) NOT NULL DEFAULT 0,local_rankint(11) NOT NULL DEFAULT 0,moneyint(11) NOT NULL DEFAULT 0,slanttext DEFAULT NULL, PRIMARY KEY (id) ENGINE=InnoDB -
您是手动创建
users表还是从迁移 创建的?如果是 migration,请修改您的帖子并放入您的users表的架构。为了更好地理解并能够帮助到您 -
在您的
users表中,验证您的id字段的排序规则是 utf8mb4_unicode_ci。错误有时可能是由于这个 -
非常感谢@Atika,你真的救了我很多爱.....它现在正在工作
标签: php mysql laravel laravel-5 eloquent