phpmysqlcodeigniterjoincount

How to SELECT rows from one table as well as COUNT() related records in other tables using CodeIgniter


$poplrRec = mysql_query("SELECT * FROM ".ADD_RECIPE." ORDER BY POPULARITY DESC LIMIT 4");
while ($poplrRec1 = mysql_fetch_array($poplrRec)) {
    $likecount = mysql_query("SELECT RECIPE_ID, COUNT(RECIPE_ID) FROM " . RECIPE_LIKE . " WHERE RECIPE_ID=" . $poplrRec1['RECIPE_ID']);
    while ($b = mysql_fetch_array($likecount)) {
        $cmnt = mysql_query("SELECT RECIPE_ID, COUNT(RECIPE_ID) FROM " . RECIPE_CMMNT . " WHERE RECIPE_ID=" . $poplrRec1['RECIPE_ID'] . " AND TYPE=0");
        while ($c = mysql_fetch_array($cmnt)) {

        }
    }
}

I use core PHP while loop and MySQL query so I have to use these type of query in MVC structure of CodeIgniter. And like here, I want result of every query separate to use in MVC structure. Each nested query intends to provide counts of related records in other tables.

Please suggest how I can implement a CodeIgniter script to populate the desired result set.


Solution

  • Try to write query following format

    $query = $this->db->get('vehicles_types');
                $result = $query->result_array();
    
                // loop through the types e.g. the parents
                foreach( $result as $key => $row )
                {
    
                    // add the "examples" e.g. the children to the result array
                    $query = $this->db->get_where('vehicles',array('type'=>$row['id']));
                    $row['examples'] = $query->result_array();
                    $result[$key] = $row;
    
                }
    
                return $result;