We have a simple database. The user table contains users. In the Accounts table, there are several accounts for each user. The topic table contains several topics for each account.
So, the user will have several accounts, and each account will have several topics. So, if I have a user with id = 1, how can I effectively query all 3 tables to get all the accounts and topics for that user?
I am currently using foreach loops that trigger a lot of sql queries. Is there a way to run a single sql query to get what I want?
Here is the code I'm using right now (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;