简体   繁体   中英

Codeigniter Joins : Result formatting based on join query

i have 2 tables in db sections and questions , each question has a section id as a FK and i am trying to fetch sections and relevant questions. Below Join Query gets me the result

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

Below is my result with all the sections and questions related to the sections,

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
        )
)

Query gets the results but format is not right. I want 1 section once in a result and then 1 index of section holds all the questions belonging to that section as seen below.

[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
                    )

            )

    )

can someone please help me how can i achieve this using joins

What you want can't be done with just joins. You need to actually run one first query that returns all the sections and then do one query for each section to get the questions. Then add those results for each section in another property of the first result.

$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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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