Magento – Conditional join in magento collection

collection;magento-1.7

I am working in magento and now i face problem in getting my info.I created collection to fetch data , but now i want to check some value if exist i want to add new inner join to that collection.I try following code but not succeeded.

$collection = Mage::getModel('mymodule/model')->getCollection();
        if($this->getRequest()->getParam('order_id')!=''){
          $collection->addFieldToFilter('main_table.order_id',$orderid);
        }
        if($user_id!='' && $user_id !='0'){  
        $collection->addFieldToFilter('main_table.t_customer_id',$user_id);
    }

        $collection->getSelect()
            ->columns('count(resp.r_ticket_id)-1 AS total_replies')
            ->joinLeft(array('dpt' => Mage::getSingleton('core/resource')->getTableName('hd_departments')),
                    'main_table.t_department_id = dpt.departments_id')
            ->joinLeft(array('ts' => Mage::getSingleton('core/resource')->getTableName('hd_ticketstatus')),
                        'main_table.t_status_id = ts.ticketstatus_id')
            ->joinLeft(array('pr' => Mage::getSingleton('core/resource')->getTableName('hd_priorities')),
                        'main_table.t_priority_id = pr.priorities_id')
                ->joinLeft(array('resp' => Mage::getSingleton('core/resource')->getTableName('hd_tickets_responses')),
                        'resp.r_ticket_id = main_table.ticket_id')

                ->group('main_table.ticket_id');

Now i want to add new join on condition basis.My condition and join are as :

 if($user_id == '0' && $this->getRequest()->getParam('id')!='')
  {
      $results = Mage::helper('mymodule')->getvisitorname($this->getRequest()->getParam('id'),'email');

      if(sizeof($results) > 0){
       $collection = $collection->getSelect('*')->joinInner(array('ureg' => Mage::getSingleton('core/resource')->getTableName('unregistereduser')),
              'main_table.ticket_id = ureg.ticket_id');

      }

But this doesn't work.how can i embed this condition to collection ? Thanks
}

Best Answer

You don't want to do

$collection = $collection->getSelect()...

because then you're assigning your $collection object to be a Select object, which is the return value of getSelect().

Just do

$collection->getSelect()...

If that doesn't work, give us more detail about the error message you're hitting.

Related Topic