提问者:小点点

SQL查询检索商业中的产品分类


在WooCommerce,我有大约8个不同类别的许多产品。当用户购买商品时,发送给他们的电子邮件会按照他们将商品添加到购物车的顺序列出商品,这看起来非常混乱。我想按产品类别订购产品,并在每个类别中按字母顺序列出产品。我认为这种“双重排序”功能最好通过修改发送电子邮件前调用的SQL查询来实现,就像这样:

$line_items = $wpdb->get_results( $wpdb->prepare( "
SELECT      order_item_id, order_item_name, order_item_type
FROM        {$wpdb->prefix}woocommerce_order_items
WHERE       order_id = %d
AND         order_item_type IN ( '" . implode( "','", $type ) . "' )
ORDER BY    order_item_id
//Would like this to be ORDER BY 'product category', 'product name' ASC//
", $this->id ) );

我不知道如何在这个查询中检索产品类别。我知道这需要一个连接,但就我的一生而言,我无法跟踪数据库表中的关键关系。

更新:WooCommerce产品被存储为具有常规WordPress分类法的帖子,所以如果有人知道如何在WordPress中检索帖子的类别,我认为这将起作用。


共1个答案

匿名用户

您可以使用以下代码,但这仅在每个产品只属于一个类别时才有用

$line_items = $wpdb->get_results( $wpdb->prepare( "
SELECT      DISTINCT woi.order_item_id, woi.order_item_name, woi.order_item_type, woim.meta_value AS product_id, t.name AS product_category
FROM        {$wpdb->prefix}woocommerce_order_items AS woi
LEFT JOIN   {$wpdb->prefix}woocommerce_order_itemmeta AS woim 
ON ( woi.order_item_id = woim.order_item_id AND woim.meta_key LIKE '_product_id' )
LEFT JOIN   {$wpdb->prefix}term_relationships AS tr
ON ( tr.object_id = woim.meta_value )
LEFT JOIN   {$wpdb->prefix}term_taxonomy AS tt ON ( tt.term_taxonomy_id = tr.term_taxonomy_id )
LEFT JOIN   {$wpdb->prefix}terms AS t ON ( t.term_id = tt.term_id )
WHERE       woi.order_id = %d
AND         woi.order_item_type IN ( '" . implode( "','", $type ) . "' )
AND         tt.taxonomy LIKE 'product_cat'
ORDER BY    product_category, woi.order_item_name
", $this->id ) );

希望这将是有用的。