【问题标题】:listing products after its parent(category)在其父(类别)之后列出产品
【发布时间】:2012-11-23 10:42:35
【问题描述】:

我对 php 比较陌生,我正在使用 oscommerce 在报告中创建类别、子类别和子类别中可用产品的列表。我已经成功地创建了类别列表,然后是子类别(子类别)。我在尝试在子类别之后列出产品时遇到了死胡同。以下是代码片段:

function category_list( $category_parent_id = 0 )
{
$sql  = 'select cd.categories_name,c.categories_id, c.parent_id, c.sort_order from ' . TABLE_CATEGORIES . ' c, ' . TABLE_CATEGORIES_DESCRIPTION . ' cd where c.categories_id = cd.categories_id AND c.parent_id='.$category_parent_id;
$res  = tep_db_query( $sql );
$cats = array();
 while ( $cat = tep_db_fetch_array( $res ) )
  {
    $cats[] = $cat;
  }
 if (count($cats) == 0)
    {
  return '';
  }
 $list_items = array();
foreach ( $cats as $cat )
 {
$list_items[] = '<tr class="dataTableRow"><td class="dataTableContent">'; 
if($category_parent_id != 0)$list_items[] = '&nbsp;&nbsp;&nbsp;';
if($category_parent_id == 0)$list_items[] = '<b>';
$list_items[] = $cat['categories_name'];


if($category_parent_id == 0)$list_items[] = '</b>';
$list_items[] = '</td><td class="dataTableContent">'; 
$list_items[] = category_list( $cat['categories_id'] );
$list_items[] = '</td></tr>'; 
}
$list_items[] = '';
return implode( '', $list_items );

}  
echo category_list();

对于列出产品,我需要使用两个表,product_to_catprod_descrip,使用 product_id 字段连接。要将其列在正确的父级中,product_to_catcat 表与 category_id 连接。我将如何在正确的类别中打印正确的产品?

【问题讨论】:

    标签: php mysql loops join parent-child


    【解决方案1】:

    假设表格看起来像这个SQL Fiddle, 那么这只是所有表之间的简单连接

    select c.parent_id, c.categories_id, cd.categories_name,
           p.product_id, pd.description
    from categories c
    join categories_description cd on cd.categories_id = c.categories_id
    left join product_to_cat p on p.category_id = c.categories_id
    left join prod_descrip pd on pd.product_id = p.product_id
    order by c.parent_id, c.categories_id, p.product_id
    

    我不知道 sort_order 如何适合这张图片。

    如果您只想要一个类别的产品,请在循环中执行以下选择

    select p.product_id, pd.description
    from product_to_cat p
    left join prod_descrip pd on pd.product_id = p.product_id
    where p.category_id = $cat['categories_id']
    

    【讨论】:

    • 有没有办法在单独的查询中运行它,而不是使用连接,只是为了提高性能?
    • @user1879415 您可以随时拆分连接并使用 php 进行连接。但这需要额外的查询,这通常比真正的连接要慢。通常,最好让数据库进行连接并专注于表布局和索引。查询在您的环境中需要多长时间?
    • 加载需要一段时间,是否有另一种方法可以在同一循环中运行单独的查询?
    • @user1879415 当然,您只能选择合适的产品。请查看更新后的答案。
    猜你喜欢
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    相关资源
    最近更新 更多