gpt4 book ai didi

php - Laravel 5.7 外键约束的形成不正确

转载 作者:行者123 更新时间:2023-11-29 09:57:21 24 4
gpt4 key购买 nike

基本上,我正在尝试将迁移上传到数据库,但遇到了一些问题,因为我正在尝试引用尚未创建的表中的列。我考虑过将它们一一迁移,但例如我有组和用户表。组有创建者(用户),用户有组。所以我无法同时引用它们,因为它们不是创建的。

这是我的错误:

PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `vote-system`.`#sql-1a08_37` (errno: 150 "Foreign key constraint is incorrectly formed")")

群组迁移

public function up()
{
Schema::create('groups', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('created_by')->unsigned();
$table->timestamps();

// Relationships
$table->foreign('created_by')->references('id')->on('users');
});
}

用户迁移

public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->ipAddress('ip');
$table->integer('votes_left');
$table->rememberToken();
$table->timestamps();
$table->integer('group_id')->unsigned();

// Relationships
$table->foreign('group_id')->references('id')->on('groups');
});
}

最佳答案

正确的方法是创建迁移来创建/删除具有较低时间戳的表(因此首先执行这些表),

然后只需添加/删除所有带有大于以前使用的时间戳的迁移的外键。这样您就不会像现在一样遇到问题。

添加外键的迁移示例:

class AddForeignKeysToMyTableTable extends Migration {

public function up()
{
Schema::table('my_table', function(Blueprint $table)
{
$table->foreign('my_field_id', ...

您可能还想尝试一些生成器来为您创建所有迁移。这将确保所有制表迁移在添加外键的迁移之前运行:

https://github.com/Xethron/migrations-generator

关于php - Laravel 5.7 外键约束的形成不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53619080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com