一次奇妙的旅行“cat
“
假设我们有以下类别层次结构:
其中wp_term_taxonomy
表包括:
我们想查询动物中的所有帖子category
其中id
是65
:
$query = new WP_Query( array( \'cat\' => 65 ) );
并尝试理解为什么生成的SQL是:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
WHERE 1=1
AND ( wp_term_relationships.term_taxonomy_id IN (15,70, 75) )
AND wp_posts.post_type = \'post\'
AND (wp_posts.post_status = \'publish\' OR wp_posts.post_status = \'private\')
GROUP BY wp_posts.ID
ORDER BY wp_posts.post_date
DESC LIMIT 0, 5
即为什么部分
65
已更改为
15, 70, 75
.
Let\'s start:
在里面
WP_Query()
我们的查询转换为:
$tax_query[0] = array( \'taxonomy\' => \'category\',
\'terms\' => array( 65 ),
\'field\' => \'term_id\',
\'include_children\' => 1
);
在给饥饿的人喂食之前:
WP_Tax_Query( $tax_query )
它从
$tax_query
大堆
在那里,它与默认值合并:
array( \'taxonomy\' => \'\',
\'terms\' => array(),
\'include_children\' => true,
\'field\' => \'term_id\',
\'operator\' => \'IN\',
);
当
WP_Query()
对象希望返回生成的SQL查询,它调用
WP_TAX_Query::get_sql()
方法
然后我们的阵列被“清理”和“变换”:
a) 它是cleaned 通过WP_TAX_Query::clean_query()
方法,导致:
array( \'taxonomy\' => \'category\',
\'terms\' => array( 61, 13, 65 ),
\'field\' => \'term_id\',
\'include_children\' => 1,
\'operator\' => \'IN\',
);
其中包含子类别
get_term_children()
.
b) 它是transformed 通过WP_TAX_Query::transform_query()
方法,其中term_id
转换为相应的term_taxonomy_id
价值观
在我们的案例中,其结果是:
SELECT term_taxonomy_id
FROM wp_term_taxonomy
WHERE taxonomy = \'category\'
AND term_id IN (15, 61, 65)
即
15, 70
和
75
:
然后,我们的税务查询如下所示:
array( \'taxonomy\' => \'category\',
\'terms\' => array( 15, 70, 75 ),
\'field\' => \'term_taxonomy_id\',
\'include_children\' => 1,
\'operator\' => \'IN\',
);
在将其添加到的SQL查询部分之前
WP_Query()
:
"join": INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
"where": AND ( tfl_term_relationships.term_taxonomy_id IN (15,70,75) )
结束;-)
您还可以直接使用WP_TAX_Query
类,以调查生成的SQL。
例如:
$tax_query = array();
$tax_query[0] = array(
\'taxonomy\' => \'category\',
\'terms\' => array( 65 ),
\'field\' => \'term_id\',
\'include_children\' => 1
);
$t = new WP_TAX_Query( $tax_query );
print_r( $t->get_sql( $GLOBALS[\'wpdb\']->posts, \'ID\' ) );
将给出以下输出:
Array
(
[join] => INNER JOIN wp_term_relationships ON (tfl_posts.ID = wp_term_relationships.object_id)
[where] => AND ( wp_term_relationships.term_taxonomy_id IN (15,70,75) )
)