joining custom tables using magento commands

▼魔方 西西 提交于 2019-12-02 10:37:57

问题


I have been trying to join two custom table using magento's commands. After searching i came across this block of generic code

$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join( array('table_alias'=>$this->getTable('module/table_name')), 
'main_table.foreign_id = table_alias.primary_key',
 array('table_alias.*'), 
'schema_name_if_different');

Following this as template I have tried to join my tables together but have only returned errors such as incorrect table name or table doesn't exist or some other error.

Just to clear things up can someone please correct me on my understanding

$collection = Mage::getModel('module/model_name')->getCollection();

Gets an instance of your model. Within that model is the table that holds the required data (for this example I shall call the table p)

$collection->getSelect()

Select data from table p

->join()

Requires three parameters to join two table together

PARAM1

array('table_alias'=>$this->getTable('module/table_name'))

'the alised name you give the table' => 'the table you want to add to the collection (this has been set up in the model folder)'

PARAM2

'main_table.foreign_id = table_alias.primary_key'

This bit i don't get (it seems straight forward though)

my main table (p) doesn't have a foreign id (it has it's primary key - is that also its foreign id)?

has to be equal to the alised name you gave in param1

PARAM3

'main_table.foreign_id = table_alias.primary_key'

get all from alised name

Where have I gone wrong on my understanding?


回答1:


Please have a look in below sql join statement, I am using it in my project and it is working perfectly.

Syntax

$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join(Mage::getConfig()->getTablePrefix().'table_name_for_join', 'main_table.your_table_field ='.Mage::getConfig()->getTablePrefix().'table_name_for_join.join_table_field', array('field_name_you_want_to_fetch_from_db'));

Working Query Example

$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join(Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar', 'main_table.products_id ='.Mage::getConfig()->getTablePrefix().'catalog_product_entity_varchar.entity_id', array('value'));

Hope this will work for you !!



来源:https://stackoverflow.com/questions/19381320/joining-custom-tables-using-magento-commands

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