SQL join in CodeIgniter with Active Record
14:08 17 Feb 2012

I'm trying to wrap my head around this, but I seem to go in circles. I'm trying to list a users topics one by one, with the quotes belonging to that specific topic underneath. If that makes sense.

I have 3 tables, like so:

[USERS] user_id username

[TOPICS] topic_id user_id topic_name

[QUOTES] quote_id topic_id quote_name

I want to be able to do something like this in my view:

Username: Thomas

Topic 1: Whatever

Quotes: One quote, another quote, and a third quote, all belonging to Topic 1.

Topic 2: Another topic from Thomas

Quotes: Yes indeed, Okay thanks, I love Stack Overflow, These quotes belong to Topic 2.

But I can't get it to work, I've been trying everything, including weird stuff like:

public function get_quotes()
{

    $this->db->select('*');
    $this->db->from('topics');
    $this->db->join('quotes', 'topic_id = quote_id');

    $query = $this->db->get();

    if($query->num_rows() > 0)
    {
        foreach ($query->result() as $row) {
            $data[] = $row;
        }
    }
    return $data;
}

Is this strange, should I instead try using 'where' instead? Something like:

$this->db->where('user', $user_id);
$this->db->where('topic', $topic_id);
$this->db->where('quote', $quote_id);

I really appreciate any help I can get, or just a finger pointed in the right direction!

php codeigniter join one-to-many query-builder