为什么只有第二个?
因为dbDelta() 支架CREATE TABLE table_name 仅限格式。一、 e.精确地“创建表”,后跟(一个空格和)表名。
更具体地说,dbDelta() 使用此正则表达式模式:CREATE TABLE ([^ ]*) 将查询解析为按表名索引的数组时;i、 e。array( \'table_1\' => \'query\', \'table_2\' => \'query\', ... ).
这是相关的code:
$cqueries = array(); // Creation Queries
...
// Create a tablename index for an array ($cqueries) of queries
foreach ( $queries as $qry ) {
if ( preg_match( \'|CREATE TABLE ([^ ]*)|\', $qry, $matches ) ) {
$cqueries[ trim( $matches[1], \'`\' ) ] = $qry;
$for_update[ $matches[1] ] = \'Created table \' . $matches[1];
}
...
}
所以在
CREATE TABLE IF NOT EXISTS table_name, 表名为(视为)
IF 而不是
table_name 由于正则表达式模式:
preg_match( \'|CREATE TABLE ([^ ]*)|\', \'CREATE TABLE IF NOT EXISTS table_name\', $matches );
var_dump( $matches );
/* Output:
array(2) {
[0]=>
string(15) "CREATE TABLE IF"
[1]=>
string(2) "IF"
}
*/
preg_match( \'|CREATE TABLE ([^ ]*)|\', \'CREATE TABLE table_name\', $matches );
var_dump( $matches );
/* Output:
array(2) {
[0]=>
string(23) "CREATE TABLE table_name"
[1]=>
string(10) "table_name"
}
*/
在您的例子中,两个查询都与该模式匹配,但由于表名都是(视为)
IF, 第一个/上一个数组项(
$queries[\'IF\']) 然后被覆盖。因此只有第二个表(在
$queries[\'IF\']) 已创建。
而WooCommerce实际上做到了not 有CREATE TABLE IF NOT EXISTS 在其代码中:
https://github.com/woocommerce/woocommerce/blob/c04f7b79f972ee854e5f5d726eb78ac04a726b32/includes/class-wc-install.php#L687
Possible Solution when using the CREATE TABLE IF NOT EXISTS table_name format
呼叫
dbDelta() 对于每个问题,如@FahamShaikh的回答:
$queries = [ // array of queries
"CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test1 ...",
"CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test2 ...",
];
foreach ( $queries as $sql ) {
dbDelta( $sql );
}
或:
dbDelta( "CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test1 ..." );
dbDelta( "CREATE TABLE IF NOT EXISTS " . $wpdb->prefix . "test2 ..." );