Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend DB select only 1 table with multiple joins

I'm using Zend DB to generate a query using the following code:

$table->select()
        ->setIntegrityCheck(false) //required for multi-table join
        ->from('modules')
        ->joinInner(
            'basket_modules',
            'modules.id = basket_modules.id')
        ->joinInner(
            'baskets',
            'baskets.id = basket_modules.basket_id')
        ->where('baskets.id = ?', $this->id);

This generates the SQL:

SELECT modules.*, basket_modules.*, baskets.*
FROM modules
INNER JOIN basket_modules ON modules.id = basket_modules.id
INNER JOIN baskets ON baskets.id = basket_modules.basket_id
WHERE (baskets.id = '3')

My problem here is with the SELECT part, it's selecting all 3 tables instead of just modules, which is the one I want. So the query I would want to generate is:

SELECT `modules`.*
FROM `modules`
#etc...

How can I do this? If I edit the query manually and run it, it returns what I want so there shouldn't be a problem with the syntax.

like image 407
yuikonnu Avatar asked Jan 14 '23 16:01

yuikonnu


2 Answers

Please look at the example in the manual Zend_Db_Select. Scroll to the Example #13.

To select no columns from a table, use an empty array for the list of columns. This usage works in the from() method too, but typically you want some columns from the primary table in your queries, whereas you might want no columns from a joined table.

$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
like image 61
Victor Smirnov Avatar answered Jan 19 '23 12:01

Victor Smirnov


you can specify column name for other table and main table like below

$table->select()
    ->setIntegrityCheck(false) //required for multi-table join
    ->from('modules',array('modules.*'))
    ->joinInner(
        'basket_modules',
        'modules.id = basket_modules.id',array('basket_modules.id'))
    ->joinInner(
        'baskets',
        'baskets.id = basket_modules.basket_id',array('baskets.id'))
    ->where('baskets.id = ?', $this->id);

so sql will be like

SELECT modules.*, basket_modules.id, baskets.id
FROM modules
INNER JOIN basket_modules ON modules.id = basket_modules.id
INNER JOIN baskets ON baskets.id = basket_modules.basket_id
WHERE (baskets.id = '3')
like image 32
liyakat Avatar answered Jan 19 '23 11:01

liyakat