我正在使用MySQL查询列出所有产品附加组件变体(色板),我能够做到这一点,以及列出与变体相关联的产品。我的问题是也列出该产品类别ID。

我没有经过MySQL的正式培训,因此对性能等的任何帮助和建议也将非常有价值!

这是我用来获取附加组件变体及其产品列表的代码,仅需要获取这些产品的类别ID。

$prod_attributes_sql = 'SELECT DISTINCT wt.slug AS term_slug, wtr.term_taxonomy_id, wpp.post_title AS wpost_title, wt.term_id AS wpt_terms, cpt.term_id AS cpt_terms
    FROM '
. " {$wc_price_table->cat_price_table_name} cpt"
. ' RIGHT OUTER JOIN wp_terms wt ON cpt.term_id=wt.term_id'
. ' INNER JOIN wp_term_relationships wtr ON wt.term_id = wtr.term_taxonomy_id'
. ' INNER JOIN wp_posts wpp ON wtr.object_id = wpp.ID'
. ' RIGHT OUTER JOIN wp_term_taxonomy ttx on wt.term_id = ttx.term_id'
. ' WHERE ttx.taxonomy IN (\'' . implode("','", $slugsnews) . '\')'
. ' ORDER BY wt.name';
$prod_attributes = $wpdb->get_results($prod_attributes_sql) or die(mysql_error());


它输出附加组件变体及其关联产品的列表。但是我将如何包括这些产品的类别ID。

让我知道是否需要添加任何进一步的说明或代码。

提前致谢!

最佳答案

我最终不得不更改查询以包括$term_id,使用以下foreach来获取条款:

        $term_id = array();
        foreach ($product_categories as $key => $category) {
            foreach ($category['terms'] as $term) {
                $term_id[] = $term->term_id;
            }
        }


并且包括在我的sql中,如下所示:

        $prod_attributes_sql = 'SELECT DISTINCT wt.slug AS term_slug, wt.name, ttx.taxonomy, wtr.term_taxonomy_id, wpp.post_title AS wpost_title, wt.term_id AS wpt_terms, cpt.term_id AS cpt_terms
            FROM '
        . " {$wc_price_table->cat_price_table_name} cpt"
        . ' RIGHT OUTER JOIN wp_terms wt ON cpt.term_id=wt.term_id'
        . ' INNER JOIN wp_term_relationships wtr ON wt.term_id = wtr.term_taxonomy_id'
        . ' INNER JOIN wp_posts wpp ON wtr.object_id = wpp.ID'
        . ' RIGHT OUTER JOIN wp_term_taxonomy ttx on wt.term_id = ttx.term_id'
        . ' WHERE cpt.term_id IN(' . implode(',', $term_id) . ')'
        . ' OR ttx.taxonomy IN (\'' . implode("','", $slugsnews) . '\')'
        . ' OR ttx.term_taxonomy_id = cpt.term_id'
        . ' ORDER BY wpp.post_title';
        $prod_attributes = $wpdb->get_results($prod_attributes_sql) or die(mysql_error());


这可行。

关于php - 列出Woocommerce产品及其类别ID-MySQL/PHP,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28191363/

10-16 23:21