· 8 years ago · Aug 05, 2018, 08:22 AM
1Magento Join Product Collection to Custom Table on Custom Attribute
2$collection = Mage::getModel('catalog/product')
3 ->getCollection()
4 ->joinAttribute('warehouse_id', 'warehouse/warehouse', 'warehouse_id', null, 'inner');
5var_dump($collection);
6
7$collection = Mage::getModel('warehouse/warehouse')->getCollection()->joinAttribute( etc.
8
9#path app/code/local/Artlantis/Warehouse/etc/config.xml
10<global>
11 <models>
12 <warehouse>
13 <class>Artlantis_Warehouse_Model</class>
14 <resourceModel>warehouse_mysql4</resourceModel>
15 </warehouse>
16 <warehouse_mysql4>
17 <class>Artlantis_Warehouse_Model_Mysql4</class>
18 <entities>
19 <warehouse>
20 <table>warehouse</table>
21 </warehouse>
22 </entities>
23 </warehouse_mysql4>
24 </models>
25 <resources>
26 <warehouse_setup>
27 <setup>
28 <module>Artlantis_Warehouse</module>
29 <connection>
30 <use>core_setup</use>
31 </connection>
32 </setup>
33 </warehouse_setup>
34 <warehouse_write>
35 <connection>
36 <use>core_write</use>
37 </connection>
38 </warehouse_write>
39 <warehouse_read>
40 <connection>
41 <use>core_read</use>
42 </connection>
43 </warehouse_read>
44 </resources>
45</global>
46
47#path app/code/local/Artlantis/Warehouse/Model/Mysql4/Warehouse.php
48<?php
49 class Artlantis_Warehouse_Model_Mysql4_Warehouse extends Mage_Core_Model_Mysql4_Abstract
50 {
51 public function _construct()
52 {
53 $this->_init('warehouse/warehouse', 'warehouse_id'); // warehouse_id PK for the table
54 }
55 }
56
57#path app/code/local/Artlantis/Warehouse/Model/Warehouse.php
58<?php
59 class Artlantis_Warehouse_Model_Warehouse extends Mage_Core_Model_Abstract
60 {
61 public function _construct()
62 {
63 parent::_construct();
64 $this->_init('warehouse/warehouse');
65 }
66 }
67
68#path /app/code/local/Artlantis/Warehouse/Model/Mysql4/Warehouse/Collection.php
69<?php
70 class Artlantis_Warehouse_Model_Mysql4_Warehouse_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
71 {
72 public function _construct()
73 {
74 $this->_init('warehouse/warehouse');
75 }
76 }
77
78#path /app/code/local/Artlantis/Warehouse/sql/warehouse_setup/mysql4-install-0.1.0.php
79<?php
80 $installer = $this;
81 $installer->startSetup();
82 $installer->run("
83 -- DROP TABLE IF EXISTS {$this->getTable('warehouse')};
84 CREATE TABLE {$this->getTable('warehouse')} (
85 `warehouse_id` int(11) unsigned NOT NULL auto_increment,
86 `warehouse_name` varchar(50) NOT NULL default '',
87 PRIMARY KEY (`warehouse_id`)
88 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
89 ");
90 $installer->endSetup();
91
92<?php
93 $warehouses = Mage::getModel('warehouse/warehouse')->load(1);
94 echo $warehouses->getWarehouseId; // field names, '_' will be remove and following word should uppercase
95 echo $warehouses->getWarehouseName;