【发布时间】:2016-06-06 18:22:21
【问题描述】:
我是 Laravel 5.2 的 Web 开发新手,我遇到了这个问题。 我有一个用户表和求职者表,我试图在求职者表中创建一个外键,该表使用迁移引用用户表,但是当我运行时 php artisan migrate 我得到错误
[照亮\数据库\查询异常]
SQLSTATE [23000]:违反完整性约束:1452 无法添加或更新子行:外键缺点
traint 失败 (jobsitelara.#sql-1a04_7d, CONSTRAINT jobseekers_user_id_foreign FOREIGN KEY (user_id
) REFERENCES users (id)) (SQL: alter table jobseekers add constraint jobseekers_user_id_foreign
签名键 (user_id) 引用 users (id))
[PDO异常]
SQLSTATE [23000]:违反完整性约束:1452 无法添加或更新子行:外键缺点
traint 失败 (jobsitelara.#sql-1a04_7d, CONSTRAINT jobseekers_user_id_foreign FOREIGN KEY (user_id
) 参考users (id))
这里是 create_users_table 的迁移
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
以及 create_jobseekers_table 的迁移
public function up()
{
Schema::create('jobseekers', function (Blueprint $table) {
$table->increments('id');
$table->string('firstname');
$table->string('lastname');
$table->enum('gender',array('male','female'));
$table->date('dateofbirth');
$table->string('occupation', 150);
$table->string('educationlevel', 200);
$table->string('cv', 150);
$table->string('skills', 200);
$table->string('address', 200);
$table->string('phonenumber', 30);
$table->integer('user_id');
$table->timestamps();
});
}
并且创建外键的迁移位于一个单独的文件中,该文件在创建表迁移运行后运行 这是 add_foreignkey_to_jobseekers_table 迁移
public function up()
{
Schema::table('jobseekers', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
我确保 Jobseekers 表中的 user_id 字段也是无符号的。 我注意到这些表在错误消息中被引用为 jobsitelara'.'#sql-1a04_8f',我不明白发生了什么。 我的代码还有什么问题?
【问题讨论】:
标签: php mysql database laravel-5.2