【发布时间】:2018-08-20 16:03:36
【问题描述】:
我有 2 个具有 one-to-many 关系的表:
posts table
___________________________________________________
| id | title | content | category_id | posts_order |
|____|_______|_________|_____________|_____________|
| 1 | test1 | testing | 1 | 0 |
| 2 | test2 | testing | 1 | 1 |
| 3 | test3 | testing | 2 | 2 |
| . | ..... | ....... | . | . |
|____|_______|_________|_____________|_____________|
categories table
___________________________
| c_id | c_name | c_order |
|______|________|_________|
| 1 | cat1 | 0 |
| 2 | cat2 | 1 |
| 3 | cat3 | 2 |
| . | ..... | ....... |
|______|_______|__________|
他们通过posts.category_id 和categories.c_id 加入,删除和更新CASCADE。
我正在寻找的是,在删除类别之前,将category_id 更新为100,这是未分类的类别。
我试过了:
global $wpdb;
//Category id to remove.
$remove_id = 2;
//Column to update
$data = array(
"category_id" => 100
);
$where = array('category_id' => $remove_id);
//Update the posts that has the id 2
$wpdb->update('posts', $data, $where);
//Delete the category
$wpdb->delete( 'categories', array( 'c_id' => $remove_id ) );
但我得到了那个错误:
WordPress database error: [Cannot add or update a child row: a foreign key constraint fails
(`myposts`.`posts`, CONSTRAINT `posts_categories` FOREIGN KEY (`category_id`) REFERENCES
`categories` (`c_id`) ON DELETE CASCADE ON UPDATE CASCADE)]
UPDATE `posts` SET `category_id` = '100' WHERE `category_id` = '2'
如何将category_id = 2 的帖子更新为100,在删除c_id = 2 的类别之前?
【问题讨论】:
标签: php mysql sql wordpress pdo