なんかエラーが発生
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`a-curation`.`post_metas`, CONSTRAINT `post_metas_ibfk_1` FOREIGN KEY (`id`) REFERENCES `posts` (`id`))
どうやら外部キーの制約がおかしいよ
qiita.com
なお、ここで外部キーとして整合性のないデータがarticleテーブルに入っていると
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails …
といったエラーが出るため、そういった不整合なデータは削除するなど何らかの対処をする必要がある
どうやら、posts
テーブルとの制約がはられていないらしい。
つーことで、Phinxでmigrationファイルを作成して実行する。
$ ./bin/cake bake migration RepasteForeignKeyPostMetas
<?php
use Migrations\AbstractMigration;
class RepasteForeignKeyPostMetas extends AbstractMigration
{
public function up()
{
$this->table('post_metas')
->addForeignKey(
'posts_id',
'posts',
'id',
[
'update' => 'RESTRICT',
'delete' => 'RESTRICT'
]
)
->save();
}
public function down()
{
$this->table('post_metas')
->dropForeignKey('posts_id');
}
}
$ ./bin/cake migrations migrate
外部キーが増えているのを確認
mysql> show create table post_metas \G
*************************** 1. row ***************************
Table: post_metas
Create Table: CREATE TABLE `post_metas` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`posts_id` bigint(20) NOT NULL,
`posts_meta_input_type_id` bigint(20) NOT NULL,
`posts_meta_status` tinyint(4) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `posts_meta_input_type_id` (`posts_meta_input_type_id`),
KEY `posts_id` (`posts_id`),
CONSTRAINT `post_metas_ibfk_2` FOREIGN KEY (`posts_meta_input_type_id`) REFERENCES `posts_input_types` (`id`),
CONSTRAINT `post_metas_ibfk_3` FOREIGN KEY (`posts_id`) REFERENCES `posts` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8
1 row in set (0.01 sec)
すると、保存もうまくいくようになりました。よかった。