We have a simple database. The User table holds users. The Accounts table holds multiple accounts for each user. The Topics table holds multiple topics for each account.
So, a user would have multiple accounts and each account would have multiple topics. So, if I have a user with id=1 how do I efficiently query all 3 tables to get all the accounts and topics for that user?
I'm currently using foreach loops that run many sql queries. Is there a way to just run one sql query to get what I want??
Here's the code I'm currently using (which is CodeIgniter code):
$data=array();
$accounts=$this->db->get_where('accounts',array('user_id'=>1));
foreach ($accounts->result() as $account) {
$tmp=array();
$topics=$this->db->get_where('topics',array('account_id'=>$account->id));
foreach ($topics->result() as $topic) {
$this->db->order_by($order_by);
$terms=$this->db->get_where('terms',array('topic_id'=>$topic->id));
array_push($tmp,array('topic'=>$topic, 'terms'=>$terms->result()));
}
array_push($data,array('account'=>$account, 'topics'=>$tmp));
}
return $data;