magento join table collection

◇◆丶佛笑我妖孽 提交于 2019-12-09 06:47:44

问题


I'm customizing Magento FAQ extension for sort faq items by category.below collection is used to get all items active faq items.

$collection = Mage :: getModel('flagbit_faq/faq')->getCollection() 
              ->addStoreFilter(Mage :: app()->getStore())
              ->addIsActiveFilter();  

there is relation table "faq_category_item"

Table structure:-

category_id    faq_id
   1              1
   2              2
   1              3 

So I decide to join two tables.I unsuccess in that. What i tried is below.

$tbl_faq_item = Mage::getSingleton('core/resource')->getTableName('faq_category_item');

$collection = Mage :: getModel('flagbit_faq/faq')->getCollection() 
                  ->getSelect()
                  ->join(array('t2' => $tbl_faq_item),'main_table.faq_id = t2.faq_id','t2.category_id')  
                  ->addStoreFilter(Mage :: app()->getStore())
                  ->addIsActiveFilter();

Whats wrong in this and how can i filter the particular category items.Please share some good links to learn Magento model collections.

Thanks in advance


回答1:


The returned type from getSelect() and join() is a select object, not the collection that addStoreFilter() and addIsActiveFilter() belong to. The select part needs to occur later in the chain:

$collection = Mage :: getModel('flagbit_faq/faq')->getCollection() 
              ->addStoreFilter(Mage :: app()->getStore())
              ->addIsActiveFilter();
// Cannot append getSelect right here because $collection will not be a collection
$collection->getSelect()
           ->join(array('t2' => $tbl_faq_item),'main_table.faq_id = t2.faq_id','t2.category_id');



回答2:


Try this function from

Mage_Eav_Model_Entity_Collection_Abstract

 /**
 * Join a table
 *
 * @param string|array $table
 * @param string $bind
 * @param string|array $fields
 * @param null|array $cond
 * @param string $joinType
 * @return Mage_Eav_Model_Entity_Collection_Abstract
 */
public function joinTable($table, $bind, $fields = null, $cond = null, $joinType = 'inner')
{

So to join tables you can do like this:

$collection->joinTable('table-to-join','left.id=right.id',array('alias'=>'field'),'some condition or null', joinType(left right inner));


来源:https://stackoverflow.com/questions/8337363/magento-join-table-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!