4

I've got a problem. I'm trying to left join two tables with Zend Framework using $select object. Unfortunatly my tables has common field 'name' and when I'm joining one with the other the results I get is that name field from table overwrites the name field from the other.

My code is something like that:

$select->joinLeft ( array ('users' => 'users' ), $this->_name . '.employee_id = users.user_id', array ('*' ) );

How I can join tables and avoid this issue?

Charles
  • 50,943
  • 13
  • 104
  • 142
Ertai
  • 1,735
  • 2
  • 23
  • 29

2 Answers2

6

Use table aliases as you would in any normal sql query!

With Zend_Db aliases are written like this:

$select = $db->select()
         ->from(array('p' => 'products'),
                array('product_id', 'product_name'))
         ->join(array('l' => 'line_items'),
                'p.product_id = l.product_id',
                array() ); // empty list of columns

The non-zend query would look like this:

SELECT p.product_id, p.product_name 
FROM products AS p 
JOIN line_items AS l ON p.product_id = l.product_id;
markus
  • 40,136
  • 23
  • 97
  • 142
4

I guess it's bit late but to get all fields from two tables you must alias all the fields

$select = $db->select()
     ->from(array('u' => 'users'),
            array('u.id'=>'u.id','u.employee_id'=>'u.employee_id','u.name'=>'u.name'))
     ->joinLeft(array('e' => 'employees'),
            'e.id = u.employee_id',
            array('e.id'=>'e.id','e.name'=>'e.name') ); 

And your array would look like:

array(
0=>array(
    'u.id'=>'1',
    'u.employee_id'=>'1',
    'u.name'=>'John Doe',
    'e.id'=>'1',
    'e.name'=>'Worker'
),
1=>array(
    ...
));