繁体   English   中英

Codeigniter 连接:基于连接查询的结果格式化

[英]Codeigniter Joins : Result formatting based on join query

我在 db部分问题中有 2 个表,每个问题都有一个部分 id 作为 FK,我正在尝试获取部分和相关问题。 下面加入查询让我得到结果

 $result= $this->db->select('t1.*, t2.*')
    ->from('sections as t1')
    ->join('questions as t2', 't1.secid= t2.secid', 'LEFT')
    ->get();
     print_r($result->result());

以下是我的结果以及与这些部分相关的所有部分和问题,

Array
(
    [0] => stdClass Object
        (
            [secid] => 1
            [secname] => Section 1
            [secimg] => 
            [qid] => 8
            [qtext] => text
        )

    [1] => stdClass Object
        (
            [secid] => 1
            [secname] => Section 1
            [secimg] => 
            [qid] => 9
            [qtext] => test
        )

    [2] => stdClass Object
        (
            [secid] => 2
            [secname] => Section 2
            [secimg] => 
            [qid] => 10
            [qtext] => test
        )
)

查询得到结果,但格式不正确。 我想要 1 个部分在结果中,然后 1 个部分索引包含属于该部分的所有问题,如下所示。

[0] => stdClass Object
    (
        [secid] => 1
        [secname] => Section 1
        [secimg] => 
        [question] => Array
            (
                [0] => stdClass Object
                    (
                        [qid] => 8
                        [qtext] => text
                        [secid] => 1
                    )

                [1] => stdClass Object
                    (
                        [qid] => 9
                        [qtext] => test
                        [secid] => 1
                    )

            )

    )

有人可以帮助我如何使用连接来实现这一点

你想要的不能只用连接来完成。 您需要实际运行一个返回所有部分的第一个查询,然后为每个部分执行一个查询以获取问题。 然后将每个部分的这些结果添加到第一个结果的另一个属性中。

$q = $this->db->get('sections');

$sections = $q->result();

foreach($sections as $key => $section) {
    $sections[$key]->questions = $this->db
        ->where('secid', $section->secid)
        ->get('questions')
        ->result();
}

return $sections;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM