您好我正在尝试创建一个具有外键的表但是当我使用php artisan migrate
命令时,我收到以下错误:
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table
`clients` add constraint clients_user_id_foreign foreign key (`user_id`)
references `users` (`id`))
我的迁移文件如下:
public function up()
{
Schema::create('clients', function($table) {
$table->increments('id');
$table->string('user_id');
$table->string('client_name');
$table->string('client_code');
$table->string('client_firstname');
$table->string('client_surname');
$table->string('client_email');
$table->text('client_brief');
$table->text('client_website');
$table->timestamps('timecreated');
$table->string('active');
});
Schema::table('clients', function($table) {
$table->foreign('user_id')->references('id')->on('users');
});
}
对于我的用户表,我使用的是Zizaco / Confide。
我不确定我的想法是什么?
答案 0 :(得分:0)
user_id
应该是整数而不是字符串
Schema::create('clients', function($table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('client_name');
$table->string('client_code');
$table->string('client_firstname');
$table->string('client_surname');
$table->string('client_email');
$table->text('client_brief');
$table->text('client_website');
$table->timestamps('timecreated');
$table->string('active');
$table->foreign('user_id')->references('id')->on('users');
});
答案 1 :(得分:0)
您可以在此处找到问题的答案:https://stackoverflow.com/a/16934874 请务必使用" $ table-> unsignedInteger(' user_id')"方法而不是您的" $ table->字符串(' user_id')"。 第一个将在数据库中创建一个int(10)列,而第二个将生成一个varchar(255)列,它与外键约束不匹配。