いくつかの結合と GROUP_BY 句を使用して、これらのいくつかのクエリを 1 つのクエリに簡単に変換できます。このアプローチの最大の欠点は、データのグループ化と区切りが少し必要になることですが、PHP は区切られたデータの「爆発」に優れています。これを試してください:
function all()
{
$this->db->select("`modules`.*, CONCAT(`layouts`.`id`,'".DATA_SUBDELIMITER."',`layouts`.`title`,'".DATA_SUBDELIMITER."',`layouts`.`file`) AS layout, CAST(GROUP_CONCAT(`sections`.`id`,'".DATA_SUBDELIMITER."',`sections`.`title` SEPARATOR '".DATA_DELIMITER."') AS CHAR) AS sections", false);
$this->db->from('modules');
$this->db->join('layouts', 'layouts.id = modules.layout_id');
$this->db->join('modules_sections', 'modules_sections.module_id = modules.id');
$this->db->join('sections', 'sections.id = modules_sections.section_id');
$this->db->group_by('modules.id');
$rows = $this->db->get()->result_array();
foreach($rows as &$row)
{
foreach($row as $k=>&$r)
{
if($k=='layout' || $k=='sections')
{
$new_r = explode(DATA_DELIMITER, $r);
foreach($new_r as &$c)
{
$e = explode(DATA_SUBDELIMITER,$c);
$c = array();
list($c['id'],$c['title']) = $e;
if(!empty($e[2])) $c['file'] = $e[2];
}
if($k=='layout') $new_r = $new_r[0];
$r = $new_r;
}
}
}
return $rows;
}
この例では、データを区切る文字に DATA_DELIMITER と DATA_SUBDELIMITER を使用しています。これらの定数を使用する場合は、おそらく application/config/constants.php ファイルで定義する必要があります。おそらく次のようになります。
define('DATA_DELIMITER','||');
define('DATA_SUBDELIMITER','##');
このコードをテストすると、次のような結果が得られました。
Array
(
[0] => Array
(
[id] => 1
[title] => Module 1
[layout_id] => 1
[layout] => Array
(
[title] => 3 Column
[id] => 1
[file] => 3_column.php
)
[sections] => Array
(
[0] => Array
(
[title] => Section 1
[id] => 1
)
[1] => Array
(
[title] => Section 2
[id] => 2
)
)
)
[1] => Array
(
[id] => 2
[title] => Module 2
[layout_id] => 2
[layout] => Array
(
[title] => 2 Column
[id] => 2
[file] => 2_column.php
)
[sections] => Array
(
[0] => Array
(
[title] => Section 1
[id] => 1
)
[1] => Array
(
[title] => Section 3
[id] => 3
)
)
)
[2] => Array
(
[id] => 3
[title] => Module 3
[layout_id] => 1
[layout] => Array
(
[title] => 3 Column
[id] => 1
[file] => 3_column.php
)
[sections] => Array
(
[0] => Array
(
[title] => Section 3
[id] => 3
)
)
)
[3] => Array
(
[id] => 4
[title] => Module 4
[layout_id] => 2
[layout] => Array
(
[title] => 2 Column
[id] => 2
[file] => 2_column.php
)
[sections] => Array
(
[0] => Array
(
[title] => Section 1
[id] => 1
)
[1] => Array
(
[title] => Section 2
[id] => 2
)
[2] => Array
(
[title] => Section 3
[id] => 3
)
[3] => Array
(
[title] => Section 4
[id] => 4
)
)
)
)