LoginSignup
1
1

More than 3 years have passed since last update.

【MySQL】外部キー制約を追加したり確認したり【ふ〜ん】

Last updated at Posted at 2020-02-13

laravelを勉強していて、マイグレーションファイルから外部キー制約を付けていたのですが、後から付けたい〜!ってなったときにMySQLの方で付ける方法知りたかったのでメモ


ALTER TABLE テーブル名 ADD FOREIGN KEY (カラム名) REFERENCES テーブル名(カラム名);

これでつく!!!

例えば、userとtwitterの関係が1対多だとすると、
twittersテーブルのuser_idと、usersテーブルのidを紐付ける必要があるので、

ALTER TABLE twitters ADD FOREIGN KEY (user_id) REFERENCES users(id);

これでいいはず。

外部キー制約を確認する方法は、

show create table twitters;

これを実行すると、

| twitters | CREATE TABLE `twitters` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `content` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `user_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `user_id` (`user_id`),
  CONSTRAINT `tasks_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |

こんなのが出てくるので、確認できるよ〜!!!!!

初心者すぎてぴえん。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1