【发布时间】:2014-03-11 18:48:29
【问题描述】:
我目前在运行迁移时收到以下错误:
SQLSTATE[HY000]: General error: 1005 Can't create table 'saferides.#sql-189_4bc' (errno: 150) (SQL: alter table `rides` add constraint rides_car_id_foreign foreign key (`car_id`) references `car` (`id`) on delete cascade)
在阅读了很多关于 Laravel 中这种性质的错误的问题后,我做了以下事情来避免它:
- 在创建主键之前不要使用外键引用主键(我通过按照以下创建顺序将表创建和外键分配保持在单独的迁移中来确保这一点 -> 键
- 确保主键和外键的类型相同(unsigned int(10))
- 明确声明存储引擎为 InnoDB
目前,我设置了迁移,以便首先创建表:
// Up function for cars table
public function up()
{
Schema::create('cars', function(Blueprint $table)
{
// Explicitly state storage engine
$table->engine = 'InnoDB';
// Primary Key
$table->increments('id')->unsigned();
// Other columns
$table->string('car_num');
$table->string('available_seats');
});
}
那么我的下一张桌子......
// Up function for rides table
public function up()
{
Schema::create('rides', function(Blueprint $table)
{
// Explicitly state storage engine
$table->engine = 'InnoDB';
// Primary Key
$table->increments('id')->unsigned();
// Other columns
$table->boolean('completed')->default(0);
$table->boolean('no_show')->default(0);
// Indexes to foreign keys
$table->integer('car_id')->unsigned()->index();
});
}
创建所有表后,我将外键添加到表中。
public function up()
{
Schema::table('rides', function(Blueprint $table)
{
$table->foreign('car_id')
->references('id')->on('car')
->onDelete('cascade');
});
}
任何有关如何解决此问题的建议将不胜感激。
【问题讨论】:
-
什么是表'saferides'?它在错误中,但您没有在代码中提及它 - 令人困惑
-
saferides 是数据库的名称。
标签: laravel foreign-keys migration