2017-02-18 113 views
0

我在学习laravel,现在我无法迁移数据库。我已经在phpmyadmin中创建了数据库,已经阅读了文档并在网络上对此问题进行了研究。然而,当我做迁移,则会持续发送相同的消息:Laravel - 无法迁移DB

SQLSTATE[HY000]: General error: 1005 Can't create table `YYYY`.`#sql-269c_1c1` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table ` cars` add constraint `cars_company_id_foreign` foreign key (`Company_id`) references `companies` (`id`) on delete cascade on update cascade) 

这是代码:

2014_10_12_000000_create_cars_table

Schema::create('cars', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('Company_id')->unsigned(); 
     $table->foreign('Company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade'); 
     $table->string('Model'); 
    }); 

2014_10_12_000000_create_companies_table

Schema::create('companies', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('Company'); 
    }); 
+0

什么数据库引擎是你使用? – Paras

回答

1

Laravel尝试运行你的迁移按1)时间,2)字母顺序排列。既然你同时给你的两个迁移,它将按照字母顺序来代替。

这实际上意味着你试图首先创建汽车表,外键约束指向一个表公司 - 但这个表尚不存在,因为它将在下一个创建移民。

正确地命名您的迁移,它应该自行解决。 :)

+0

我已经更改了文件名中的日期以便让它们按顺序迁移。它的工作原理。谢谢!! – Adato

1

是因为乔尔赛义德注意迁移命名约定。 要避免这些错误,你可以使用迁移命令

第一步命令行下面
运行

php artisan make:migration create_companies_table 

第二步

这将使空白迁移模式在数据库中,然后编辑它就像下面那样

Schema::create('companies', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('Company'); 
    }); 

步骤3中的命令行下面 运行

php artisan make:migration create_companies_table 

第4步 这将使空白迁移模式在数据库中,然后编辑它像下面

Schema::create('cars', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->integer('Company_id')->unsigned(); 
     $table->foreign('Company_id')->references('id')->on('companies')->onDelete('cascade')->onUpdate('cascade'); 
     $table->string('Model'); 
    }); 
+0

Didnt知道它可以进行迁移文件。现在起作用了。谢谢! – Adato

+0

如果它帮助你,请将答案标记为正确 – sumit

+0

我该怎么做?我不知道我们可以将答案标记为正确。 – Adato