1

I am using CodeIgniter

I have two tables -

Company int id , varchar name

Employee int id, varchar name , int company_id

I have a simple controller called Employees Controller

<?php 

class Employees extends CI_Controller {

    public function index()
           {

----
----
$data['employees'] = $selected_employees;
$this->load->view('employees/index',$data);
}

}

This controller passes an array of Employees to the view . So inside my view , I can freely use employees[4].name , employees[3].id etc

Now If I want to show the name of the Company of the employees , it seems the only way is the Controller should pass another array with the name of the companies to the view . Is there any better way to achieve this - so that the controller doesnt have to explicitly have to send the data ?

For eg - say I want to access employees[4].company.name I have been spoilt by Rails . I used to take these for granted .

geeky_monster
  • 8,672
  • 18
  • 55
  • 86

2 Answers2

4

The best way to go about this is using a join statement in your SQL query. The SQL query would typically look something like the following:

SELECT * FROM Employee JOIN Company ON Employee.company_id = Company.id

However, CodeIgniter's active record class will help us to simplify this (see http://ellislab.com/codeigniter/user-guide/database/active_record.html). In your model, you could write your query like so:

$this->db->select('*');
$this->db->from('Employee');
$this->db->join('Company', 'Employee.company_id = Company.id');
$query = $this->db->get();

You can tweak this to select the exact data that you want like you would any SQL query:

$this->db->select('Employee.id, Employee.name, Employee.company_id, Company.name AS company_name');

You can also add left, right, outer, inner, left outer, or right outer as a third parameter to the $this->db->join() function to allow for left joins, right joins, etc.

I would recommend using the Active Record class when possible in your CodeIgniter applications. It will help keep your queries clean, organized, and readable.

RJ Spiker
  • 330
  • 1
  • 6
2

Do a join on your model

public function get_ selected_employees(){
    $this->db->select('Employee.*, Company.name as company_name');
    $this->db->from('Employee');
    $this->db->join('Company', 'Employee.company_id = Company.id');
    return $this->db->get()->result();
}

To get the company name just do employees[4].company_name

Fabio Antunes
  • 22,251
  • 15
  • 81
  • 96
  • 1
    This is fine but there will be a conflict as both tables have `name` fields, just need to use `$this->db->select('Employee.*, Company.name as company_name');` or similar. – Adam Westbrook Mar 08 '13 at 15:39
  • Thanks Fabio. This is of great help . I hadnt thought of the possibility of using a join . Cheers ! – geeky_monster Mar 09 '13 at 02:11