I’ve been hacking away at CodeIgniter for a week or so, only because I don’t have the ability to understand RoR. I’ve managed to create some rudimentary models, views and controllers but I am now at a point where I have to start considering the fact that I am using multiple models.
My question may be related to basic SQL, but I expect that there is functionality in CodeIgniter which permits returned rows from having certain data fields be replaced with information from other tables. If I knew what this concept was called in SQL, then I would at least know what to look for in the Docs, but I am only a beginner. I’d like to at least have some basic knowledge here so I can read up on the details.
For example, let’s say I have a companies table (company model) which has only two fields, an ‘id’ set as the primary key, and a ‘Company_name’ which is varchar. In addition, let’s say I have a table of stores (store model) which has four fields like ‘address’, ‘id’ (primary key), and company_id which is the index in the companies table.
The companies could be something like:
ID Company_name
------------------------------------------------
1 CompanyA
2 CompanyB
3 CompanyC
The stores could be something like:
ID Store_name Address Company_ID
------------------------------------------------
1 StoreA 12 Main St. 1
2 StoreB 33 First Ave. 1
3 StoreC 9 Broad Rd. 2
4 StoreD 873 Wide Blvd. 3
5 StoreE 8103 Water St. 1
Where the CompanyID field relates the table back to the companies table.
If I do a basic query in CodeIgniter to return all ‘stores’ as:
$this->db->get('stores');
I will be able to go through the result row by row, but the Company_ID field will still be just an index value. Is there a way to perform a query such that the Company_ID field is automatically replaced by the appropriate company name from the companies table in the returned results? The idea would be that I want to create a resulting table which looks like the one below:
Store Name Address Company Name
------------------------------------------------
StoreA 12 Main St. CompanyA
StoreB 33 First Ave. CompanyA
StoreC 9 Broad Rd. CompanyB
StoreD 373 Wide Blvd. CompanyC
StoreE 8103 Water St. CompanyA
An easy real-world example would be fast food chain stores belonging to a parent company or something like that.
Not sure how else to explain this. :/
What you’re looking for is a SQL join. You can do it in CodeIgniter like this.
Personally, I just prefer to write the query myself.