0

ページと呼ばれるデータベーステーブルにレコードがあります

次のような構造:

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

しかし、グループ化などを使用して結果を並べ替える必要があるため、同じparent_idを持つdbのすべての行をグループ化し、その後get()を作成すると、結果は次のようになります。

Africa
    Egypt
America
    Canada
    Mexico
Europe
    Germany
    France
    Spain

ここで、parent_id = 0 はアフリカ、アメリカ、ヨーロッパです

エジプトには、親のIDに応じて、たとえばparent_id = 1カナダとメキシコparent_id = 2などがあります

どうやってするか?

ところで。テキストのインデントと css は問題ありません。foreach ループ自体の結果配列に興味があります。

4

1 に答える 1

2

このクエリはそれを行う必要があります:

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();
于 2013-03-12T11:58:39.580 に答える