magento using join in grid.php prepareCollection

Pau*_*ulo 5 join magento

Can someone tell me how to make a join within magento

Here is the problem:

<?//kleurtjes
$collection= Mage::getModel('faq/faq')->getCollection();

$collection->getSelect()->join(array('faqcat' => $this->getTable('faqcat/faqcat')), 'faqcat.faqcat_id=faq.faqcat_id' , array('faqcat.*'));

?>
Run Code Online (Sandbox Code Playgroud)

i am trying to make a join with the table faqcat where i use the key faqcat_id .

futher i want that faqcat.name + faq.faq_id are being selected cos these are the values i want to use in colums.

<?
  protected function _prepareColumns()
  {

      $this->addColumn('faq_id', array(
          'header'    => Mage::helper('faq')->__('ID'),
          'align'     =>'right',
          'width'     => '50px',
          'index'     => 'faq_id',
      ));

      $this->addColumn('name', array(
          'header'    => Mage::helper('faqcat')->__('Titel'),
          'align'     =>'left',
          'index'     => 'name',


      ));

}
?>
Run Code Online (Sandbox Code Playgroud)

after trying 1000 combinations i dont know what to do anymore ... who is willing to help me

this is the complete function:

<?
  protected function _prepareCollection()
  {

     $collection= Mage::getModel('faq/faq')->getCollection();
     //$collection->getSelect()->join(array('faqcat' => $this->getTable('faqcat/faqcat')), 'faqcat.faqcat_id=faq.faqcat_id' , array('faqcat.*'));
     $id = Mage::getModel('customer/session')->getCustomer()->getId();

      $this->setCollection($collection);

     // }
      return parent::_prepareCollection();
  }

?>
Run Code Online (Sandbox Code Playgroud)

只是为了清楚这是我想要的sql,但接着是magento方式

<?//kleurtjes
SELECT faq.faq_id as id, faqcat_name as name
FROM faq
JOIN faqcat
USING ('faqcat_id')
?>
Run Code Online (Sandbox Code Playgroud)

小智 5

试试这个:

$collection->getSelect()
          ->join($this->getTable('faqcat/faqcat'), "faqcat.faqcat_id = main_table.faqcat_id", array(faqcat.*));
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式查看实际运行以获取集合的sql:

Mage::log($collection->getSelect()->__toString());
Run Code Online (Sandbox Code Playgroud)

Varien_Db_Select类基于Zend_Db_Select,因此Zend文档是一个很好的参考.


R T*_*R T 5

我刚开始开发magento扩展(爱它),这是我必须从两个表格中显示网格的第二部分.(噢).但是在上网之后并没有那么容易,我通过这样做实现了我的结果.

$collection = Mage::getModel('linkdirectory/linkdirectory')->getCollection();
      $resource = Mage::getSingleton('core/resource');

      $collection->getSelect()
              ->join(
                      array('lk'=>$resource->getTableName('linkdirectory/linkcategory')),
                     'lk.cat_id = main_table.cat_id',
                      array('lk.cat_title','lk.cat_id')
                      );
Run Code Online (Sandbox Code Playgroud)

/*我正在显示这个*// SELECT main_table.,lk.cat_title,lk.cat_idFROM linkdirectoryAS main_tableINNER JOIN linkcategoryAS lkON lk.cat_id = main_table.cat_id*/

/*打印当前查询*/

$收藏 - > printlogquery(真);退出;