之前我曾获得过如何将多个表连接在一起以使此导航列表正常工作的帮助,因为您可以看到我已经完成了此操作,但现在我正在尝试在列表中输出导航,但它正在重复顶部和底部类别基于这些类别中的产品数量:这是显示我的表格设置的上一个链接:
Joining 2 tables with foreign key id
这是我的代码试图正确回显导航。
try
{
$result = $pdo->query('SELECT product.*, bottom_category.bottom_name, top_category.top_name
FROM product
INNER JOIN bottom_category ON bottom_category.id = product.bottom_category_id
INNER JOIN top_category ON top_category.id = bottom_category.top_category_id
ORDER BY top_category.id,bottom_category.id');
} // end try
catch (PDOException $e)
{
echo 'There was a error fetching the products.' . $e->getMessage();
exit();
} // end catch
$products = array();
foreach ($result as $row)
{
$products[] = array('top_name' => $row['top_name'],
'bottom_name' => $row['bottom_name']);
}
?>
<div class="sidebar">
<h4 class="sidebar-header">Select Products</h4>
<form class="nav-search-form">
<input type="search" name="search" placeholder="Search products">
</form>
<nav class="sidebar-links">
<ul>
<li><a id="red" href="/semtronics/index.php">New Products</a></li>
<?php
foreach ($products as $product):
?>
<li><a href="#"><?php echo htmlspecialchars($product['top_name']);?></a>
<ul>
<li><a href=""><?php echo htmlspecialchars($product['bottom_name']);?></a></li>
</ul>
</li>
<?php endforeach; ?>
</ul>
</nav>
</div><!-- sidebar -->
现在一切正常,唯一的问题是它是根据链接到该类别的产品数量来复制导航列表。
答案 0 :(得分:0)
我认为您需要另一种解决方案来完成此任务。 你不需要这里的产品
查询您需要的是:
select bottom_category.name as bottom_name, top_category.name as top_name
from bottom_category
inner join top_category on top_category.id = bottom_category.top_category_id
order by top_category.id, bottom_category.id
我在想你的代码中需要来自product
表的东西,但如果没有 - 请使用上面的SQL查询。
或者您需要产品表中的数据?
如果您需要product
,则可以运行
select bottom_category.name as bottom_name, top_category.name as top_name
from product
inner join bottom_category on bottom_category.id = product.bottom_category_id
inner join top_category on top_category.id = bottom_category.top_category_id
group by product.bottom_category_id
order by top_category.id, bottom_category.id
但请注意,您不知道在这种情况下将使用哪一行产品