Laravel在迁移文件上添加外键

时间:2015-11-08 19:57:30

标签: php mysql laravel laravel-5.1

我在数据库中的card_price表上有这个结构:

CREATE TABLE IF NOT EXISTS `card_price` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `card_price` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `user_id` tinyint(3) unsigned NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

users的结构:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `family` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `username` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

我正在使用migration文件创建此表,例如:

card_price

Schema::create('card_price',function(Blueprint $table){
    $table->increments('id');
    $table->string('card_price');
    $table->tinyInteger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users');
    $table->timestamps();
});

users

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name','20');
    $table->string('family','25');
    $table->string('username','15');
    $table->string('password','64');
    $table->string('email','20');
    $table->string('remember_token','100');
    $table->timestamps();
});

使用此迁移文件我正在尝试使用user_id表上的card_priceid表上的users创建外键。不幸的是我收到了这个错误:

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
  : alter table `card_price` add constraint card_price_user_id_foreign foreig
  n key (`user_id`) references `users` (`id`))

  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

1 个答案:

答案 0 :(得分:1)

由于外表中的数据类型不匹配,您收到此错误。您应该为引用它的父表和子表表列使用相同的数据类型。

user_id表格中card_price的数据类型更改为INT UNSIGNED NOT NULL;

首先使用以下查询更改您的表:

ALTER TABLE `card_price` 
CHANGE COLUMN `user_id` `user_id` INT UNSIGNED NOT NULL ;

查询外键引用:

ALTER TABLE `card_price` 
ADD CONSTRAINT `fk_users`
  FOREIGN KEY (`user_id`)
  REFERENCES `users` (`id`)
  ON DELETE NO ACTION
  ON UPDATE NO ACTION;