Search code examples
mysqldatabasedoctrine-ormcodeigniter-2

Append data from Reference table to another table in Doctrine and Codeigniter


I have a Departments reference table like:

Id Name
1. Dept1
2. Dept2
3. Dept3

I have a Users table like:

Id Name  
1. User1 
2. User2

On adding a user I want to be able to assign them a department. However I dont want to store the department name in the user table, hence the reference table. So I was thinking I should have a Dept_id field in the User table so as to make the reference to the Department table.

Problem is I need to output the User id, User Name and Department name after adding the user. Challenge is I am doing this by:

$array['users'] = Users::getUsersAll();
$this -> table -> set_heading(array('id', 'Name');

In the model the getUsersAll() method contains:

$query = Doctrine_Query::create() -> select("id,Name") -> from("users")

In the view, I generate the table by:

echo $this -> table -> generate($users);

How then would I be able to query and output the name of the department and append it to the table containing the the rest of the user data?


Solution

  • As per your description, user class will be something similar.

    class User
        {
    
        /** Other members ...... **/
    
        /** @ManyToOne(targetEntity="Department") */
        public $department;
    
        }
    

    You can access the Department name from User object by $user->department->name