0

I'm working on a codeigniter project.

Here are my tables

category
cid cname
5   general
6   science
7   math

books
bid bname
12  first
13  second
14  third
15  fourth
16  fifth
17  sixth

dir
id  bid     cid
1   12      5
2   13      6
3   14      7
4   15      6
5   16      5
6   17      5

As you can see joining the tables is easy but here is what I need to do.

Create a function that will give me category name(cname) and the number of books in that category. For example the outcome should be like

general 3
science 2
math    1

here is my WIP model

function category_details(){
        $this->db->order_by('cname','asc');
        $query=$this->db->query('Select * from dir join category on category.cid=dir.cid join books on dir.bid=books.bid');
        return $query->result_array();
}

Any help would be much appreciated.

1
  • what's output now ?? Commented Apr 21, 2017 at 4:41

1 Answer 1

0

The query should be like this to get expected result

Select category.cname,count(dir.cid) from dir join category on category.cid=dir.cid join books on dir.bid=books.bid group by category.cname

And your function should be like this

function category_details(){
        $this->db->order_by('cname','asc');
        $query=$this->db->query('Select category.cname,count(dir.cid) from dir join category on category.cid=dir.cid join books on dir.bid=books.bid group by category.cname');
        return $query->result_array();
}

you can refer this code COUNT / GROUP BY with active record? for proper CI query.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.