我不知道我做的是对还是错,请不要评判我…我想要做的是,如果一条记录属于parent,那么它将拥有与之关联的parent id。下面让我向您展示我的表模式。

我有两列ItemCategoryID和ItemParentCategoryID
假设ItemCategoryID =4上的一条记录属于ItemCategoryID =2,那么ID为4的列ItemParentCategoryID的ID将为ItemCategoryID。
我的意思是在它自己的表中有一个循环..
但问题是如何运行select查询:P我的意思是显示所有的父母和孩子分别与他们的父母。
发布于 2013-10-25 17:44:27
我不认为你想/可以在你的查询中这样做,因为你可以嵌套很长一段路。
您应该创建一个在检索类别时调用自身的getChilds函数。这样,您可以嵌套两个以上的标高。
function getCategory()
{
// Retrieve the category
// Get childs
$childs = $this->getCategoryByParent($categoryId);
}
function getCategorysByParent($parentId)
{
// Get category
// Get childs again.
}发布于 2013-10-25 17:46:58
试试这个:
function all_categories(){
$data = array();
$first = $this->db->select('itemParentCategoryId')->group_by('itemParentCategoryId')->get('table')->result_array();
if( isset( $first ) && is_array( $first ) && count( $first ) > 0 ){
foreach( $first as $key => $each ){
$second = $this->db->select('itemCategoryId, categoryName')->where_in('itemParentCategoryId', $each['itemParentCategoryId'])->get('table')->result_array();
$data[$key]['itemParentCategoryId'] = $each['itemParentCategoryId'];
$data[$key]['subs'] = $second;
}
}
print_r( $data );
}发布于 2013-10-25 17:51:22
MySQL不支持递归查询。可以通过recursive calls to a stored procedure模拟递归查询,但这不是很好,而且不是最优的。
有other ways to organise your data,这些结构允许非常高效的查询。
https://stackoverflow.com/questions/19586167
复制相似问题