簡體   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