我有如下表格,
id | name |parent
---| --- | ---
1 |vehicle|0
2 |car |1
3 |test |0
4 |maruti |2
5 |alto |4
6 |test2 |3
我的类别 ID 为 5。现在我想要 ID 为 5 的第一个父类别。
id 5 的第一个父类别是 1(车辆)
为此我需要运行 4 个查询来获取它。
例如,
public function getParentCategory($catId)
{
$cat = mysql_fetch_array(mysql_query('select id,parent from category where id=$catId'));
if ($cat['parent'] == 0) {
return $cat['id'];
} else {
return $this->getParentCategory($cat['id']);
}
}
现在上面的函数运行了 3 次以获取类别 alto
的第一个父级的 id
那么,有没有什么简单的方法可以在不递归运行查询的情况下更轻松地获得结果?
最佳答案
我认为您应该从 db 中获取所有类别,然后在 php 中选择当前类别。 例子
$categories = mysql_fetch_array(mysql_query('select id,parent from category'));
foreach($categories as $cat){
$this->categories[$cat['id']][] = $cat;
}
选择类别:
public function getParentCategory($catId)
{
if ($this->categories[$catId]['parent'] == 0) {
return $this->categories[$catId]['id'];
} else {
return $this->getParentCategory($this->categories[$catId]['parent']);
}
}
关于php - 如果表有嵌套记录,我如何从 mysql 表中获取主要值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40859534/