【问题标题】:Hierarchical query using Active Record使用 Active Record 进行分层查询
【发布时间】:2013-02-27 21:11:15
【问题描述】:

我的数据库表中有名为 pages

的记录

结构如下:

id | parent_id | title

如果 parent_id == 0 表示该行是父行

如果 parent_id != 0 表示该行是子行

我可以使用 CodeIgniter activerecord 获取所有记录,例如:

$query = $this->db->get('pages');

结果是这样的:

Europe
Mexico
Spain
Africa
Germany
Canada
America
Egypt
France

但我需要使用一些 groupby 或其他东西对结果重新排序,以便它将 db 中具有相同 parent_id 的所有行分组,然后生成 get(),因此结果将如下所示:

Africa
    Egypt
America
    Canada
    Mexico
Europe
    Germany
    France
    Spain

其中 parent_id = 0 是非洲、美洲和欧洲

埃及有例如parent_id = 1 加拿大和墨西哥 parent_id = 2 等等根据他们父母的ID

怎么做?

顺便说一句。文本缩进和css都没问题,我只是好奇foreach循环本身的结果数组。

【问题讨论】:

  • 有什么想法可以解决这个问题吗?
  • 我不明白你的桌子的结构,你的父母和孩子在同一张桌子上吗?
  • 使用 MySQL(缺少递归查询),您不能仅使用 SQL 来做到这一点。您需要在客户端代码或存储过程中执行此操作
  • 我可以使用 2 个 foreach 循环(一个在另一个循环中)来做到这一点,但我在想也许它可以使用活动记录来完成并在我的模型中完成

标签: mysql arrays codeigniter activerecord


【解决方案1】:

这个查询应该这样做:

select 
    c2.id, c1.title as continent, c2.name as country
from
    country as c1
        left outer join country as c2 ON (c1.id = c2.parent_id)
where
    c2.parent_id != 0
order by c1.title , c2.title

根据您的示例数据,这将产生:

8   Africa  Egypt
6   America Canada
2   America Mexico
9   Europe  France
5   Europe  Germany
3   Europe  Spain

更新: 如果您想在同一字段中混合使用各大洲和国家:

select 
    c2.id, c2.title as country
from
    country as c1
    left outer join
        country as c2 ON (c1.id = c2.parent_id or c1.id = c2.id and c2.parent_id = 0)
where
    c2.title is not null
order by 
    case 
        when c2.parent_id = 0 then c2.id else c2.parent_id end,
        c2.parent_id

这将为您提供以下输出:

1   Europe
3   Spain
9   France
5   Germany
4   Africa
8   Egypt
7   America
6   Canada
2   Mexico

对于在codeigniter中使用,最简单的方法是不使用活动记录,只是一个简单的查询:

$sql = 'select 
    c2.id, c2.title as country
from
    country as c1
    left outer join
        country as c2 ON (c1.id = c2.parent_id or c1.id = c2.id and c2.parent_id = 0)
where
    c2.title is not null
order by 
    case 
        when c2.parent_id = 0 then c2.id else c2.parent_id end,
        c2.parent_id'

$result = $this->db->query($sql)->result();

【讨论】:

  • 谢谢,但我需要它也包括大洲作为单独的记录。这样他们就失踪了。顺序可能是您使用的字母顺序,但现在不是问题。重要的是父母也包括在内。你也可以使用 CodeIgniter 的活动记录吗?
  • 谢谢,你能用 CodeIgniter 的活动记录来做吗?
  • 我不认为使用 CI 活动记录可以很好地完成 order by。我会改为通过 $this->db->query($sql)->result() 运行查询。
  • 如果可能的话,你能解释一下或者写代码吗?提前致谢。
猜你喜欢
  • 2011-10-22
  • 1970-01-01
  • 2012-06-05
  • 2013-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多