Search code examples
databasecodeignitermysqlicodeigniter-3codeigniter-2

Codeigniter SUM query brings only one row


When I add SUM in Codeigniter SELECT, it returns only one row. But when I remove it, it returns all of the possible matching entries.

$this->db->where('posts.status',1)
     ->select('posts.title')
     ->select('posts.description')
     ->select('posts.posted_by')
     ->select('posts.posted_on')
     ->select('posts.category')
     ->from('posts')

     ->join('categories','posts.category=categories.id','LEFT')
     ->select('categories.title as cat_title')

     ->join('users','users.id=posts.posted_by','LEFT')
     ->select('users.username')
     ->select('users.first_name')
     ->select('users.last_name')

     // this section is causing to return only one entry/row, 
     // when I remove/comment this section, it brings the desired results
     ->join('votes','votes.post_id=posts.id',"LEFT")
     ->select('SUM(upvote) as upvote_count')
     ->select('SUM(downvote) as downvote_count')

     ->get()
     ->result_object();

Solution

  • Try to add:

    ->group_by('posts.id')
    

    After

    ->select('SUM(downvote) as downvote_count')
    

    So now query will be:

    $this->db->where('posts.status',1)
        ->select('posts.title')
        ->select('posts.description')
        ->select('posts.posted_by')
        ->select('posts.posted_on')
        ->select('posts.category')
        ->from('posts')
    
        ->join('categories','posts.category=categories.id','LEFT')
        ->select('categories.title as cat_title')
    
        ->join('users','users.id=posts.posted_by','LEFT')
        ->select('users.username')
        ->select('users.first_name')
        ->select('users.last_name')
    
        // this section is causing to return only one entry/row, 
        // when I remove/comment this section, it brings the desired results
        ->join('votes','votes.post_id=posts.id',"LEFT")
        ->select('SUM(upvote) as upvote_count')
        ->select('SUM(downvote) as downvote_count')
        ->group_by('posts.id')
    
        ->get()
        ->result_object();