Duplicate rows in meta table, any known relations in WC?
题
I am doing a migration from very old to current wordpress/woocommerce and while investigating the data I found out that there are more than one row for a products _stock
meta key. The same for other meta_key
s.
I found an old discussion here https://core.trac.wordpress.org/ticket/10905
Which relations (tables) utilize multiple meta values in the meta table?
Which relations break if I delete all but one of the values?
Can I safely force a UNIQUE index?
ALTER TABLE `wp_postmeta` ADD UNIQUE (
`post_id` ,
`meta_key` ,
`meta_value`
);
解决方案
What you propose would break a lot of plugins and internals of WordPress. Post meta keys are not unique.
This is supported at the API level too:
// on save...
add_post_meta( $post_id, 'lead', 'Tom' );
add_post_meta( $post_id, 'member', 'Bob' );
add_post_meta( $post_id, 'member', 'Janet' );
add_post_meta( $post_id, 'member', 'Alice' );
add_post_meta( $post_id, 'member', 'David' );
add_post_meta( $post_id, 'member', 'Siobhan' );
add_post_meta( $post_id, 'member', 'Mikoto' );
add_post_meta( $post_id, 'member', 'Hans' );
// on the frontend...
$lead = get_post_meta( $post_id, 'lead', true );
$members = get_post_meta( $post_id, 'member' );
echo "<p>The leader is: ".$lead."</p>";
echo "<p>Members:</p><ul>";
foreach ( $members as $member ) {
echo "<li>".$member."</li>";
}
echo "</ul>";
Notice the third argument of get_post_meta
, if true
it. returns the first value found, but it false
it returns all values found as an array.
It's incredibly useful for repeater fields. As a result, there may be perfectly good reasons to store multiple post meta key/value rows for a post that have the same values.
As for why WooCommerce might be storing multiple rows of the same data, you would have to ask on a WooCommerce forum or support avenue, as 3rd party plugins are offtopic. here