【发布时间】:2016-10-12 05:37:37
【问题描述】:
如何将所有 woocommerce 产品类别放入单独的 mysql 表中?
【问题讨论】:
标签: mysql wordpress woocommerce
如何将所有 woocommerce 产品类别放入单独的 mysql 表中?
【问题讨论】:
标签: mysql wordpress woocommerce
使用此代码。注意:听起来您正试图从同一个表的不同行中获取多条数据。
$sql = "SELECT p.id, p.post_title, p.guid, p.post_type, m.meta_key, m.meta_value, meta_sp.meta_value as sale_price, meta_ap.meta_value as additional_price
FROM wp_posts p
INNER JOIN wp_postmeta m
INNER JOIN wp_postmeta meta_sp ON p.id=meta_sp.post_id
AND meta_sp.meta_key='sale_price'
INNER JOIN wp_postmeta meta_ap ON p.id=meta_ap.post_id
AND meta_ap.meta_key='additional_price'
WHERE p.id=m.post_id
AND m.meta_key='_rentable' AND m.meta_value='yes'
";
【讨论】:
好吧,我使用的是代码方式,因为我没有找到任何使用 mysql 查询的特定解决方案,因为它的 3 级深度类别。它的工作和测试代码。
$all_categories = get_categories(array("taxonomy" => "product_cat", "parent" => 0, "show_count" => true));
foreach ($all_categories as $cat) {
$category_id = $cat->term_id;
$sub = get_categories(array("taxonomy" => "product_cat", "parent" => $category_id));
$wpdb->query( $wpdb->prepare( "INSERT INTO product_category(cat_id, cat_name, parent_id)
VALUES ( %d, %s, %d )", array($category_id, $cat->name, $cat->category_parent)));
if(!empty($sub)){
foreach($sub as $subcat){
if($subcat->category_parent != ''){
$subcatid = $subcat->term_id;
$wpdb->query( $wpdb->prepare( "INSERT INTO product_category(cat_id, cat_name, parent_id)
VALUES ( %d, %s, %d )", array($subcatid, $subcat->name, $subcat->category_parent)));
}
$thirdlevel = get_categories(array("taxonomy" => "product_cat", "parent" => $subcatid));
if(!empty($thirdlevel)){
foreach($thirdlevel as $thirdcat){
if($thirdcat->category_parent != ''){
$lastcatid = $thirdcat->term_id;
$thirdarray = array('cat_id'=> $lastcatid, 'cat_name'=>$thirdcat->name, 'parent_id'=> $thirdcat->category_parent);
$wpdb->query( $wpdb->prepare( "INSERT INTO product_category(cat_id, cat_name, parent_id)
VALUES ( %d, %s, %d )", array($lastcatid, $thirdcat->name, $thirdcat->category_parent)));
}
}
}
}
}
}
在这些代码之后,您可以使用此查询从新表中获取所有数据。
SELECT t1.cat_id AS lev1, t1.cat_name AS lev1name, t2.cat_id AS cat2, t2.cat_name AS cat2name, t3.cat_id AS lev3, t3.cat_name AS lev4 FROM product_category AS t1 左加入 product_category AS t2 ON t2.parent_id = t1.cat_id LEFT JOIN product_category AS t3 ON t3.parent_id = t2.cat_id
【讨论】: