简体   繁体   中英

Zend Framework query issue

Look at this code:

$sql = $this->getAdapter()->select()
        ->from(array('mab' => 'module_adv_banner'))
        ->joinLeft(array('mafb' => 'module_adv_filebanner'),'mab.id = mafb.id_banner',array('source','type'))
        ->joinLeft(array('macb' => 'module_adv_contentbanner'),'mab.id = macb.id_banner',array('content','type'))
        ->where('mab.id = ?', $this->_id)
        ->order('position asc');

In this query I use 3 tables. First with 'mab' alias - is the main banners table. Two another tables are 'mafb' and 'macb' are specific tables for different banner types. In case the banner is image or swf, it is stored in 'mafb' table, in case of banner-informer, I use another table - 'macb'

In this query I select all required elements of banner. Only one of two specific tables have row with id_banner = mab.id = $this->_id, and each of this tables have field 'type'. If it finds this row in first table, value of 'type' is null, because it is overwritten by second table 'type' value. How can I solve that problem?

Best Regards, Ahmed.

ps sorry if my explanation is difficult, I do not have good english knowledge.

Not going into the details of why you keep 2 tables for one thing (banners)... try prepending the tablename to the fields being selected:

  $sql = $this->getAdapter()->select()
        ->from(array('mab' => 'module_adv_banner'))
        ->joinLeft(array('mafb' => 'module_adv_filebanner'),'mab.id = mafb.id_banner',array('mafb.source','mafb.type'))
        ->joinLeft(array('macb' => 'module_adv_contentbanner'),'mab.id = macb.id_banner',array('macb.content','macb.type'))
        ->where('mab.id = ?', $this->_id)
        ->order('position asc');

That will give you 4 fields instead of 2 which you can use in PHP and sort out the thing you need. Although it's a bit strange, that the adapter didn't namespace colliding field names.

BTW, it is sometimes more convenient to pass array() as the 3rd argument to join() and use columns() to define the fields you actually want to pull out.

Use $key => $value notation to create aliases:

->joinLeft(array('mafb' => 'module_adv_filebanner'),'mab.id = mafb.id_banner',array('mafb.source', 'mafb_type' => 'type'))
->joinLeft(array('macb' => 'module_adv_contentbanner'),'mab.id = macb.id_banner',array('macb.content','macb_type' => 'type'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM