
Magento 2.x – How to easily join tables or models.
With the following snippet, you will be able to join as many tables or models as you want. Bear in mind, that if you are working with a custom model, you should have created the corresponding ResourceModel like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php namespace Offset101\Helloworld\Model\ResourceModel\Hello; class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { /** * @var string */ protected $_idFieldName = 'id'; /** * Define resource model * * @return void */ protected function _construct() { $this->_init('Offset101\Helloworld\Model\Hello', 'Offset101\Helloworld\Model\ResourceModel\Hello'); } } |
Afterwards, and considering that you want to make the join in a block, we will need something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php namespace Offset101\Helloworld\Block; class Hello extends \Magento\Framework\View\Element\Template { protected $_helloModelFactory; protected $_resource; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Offset101\Helloworld\Model\HelloFactory $helloModelFactory, \Magento\Framework\App\ResourceConnection $Resource ) { $this->_helloModelFactory = $helloModelFactory; $this->_resource = $Resource; parent::__construct($context); } public function getJoinData(){ $collection = $this->_helloModelFactory->create()->getCollection(); $second_table_name = $this->_resource->getTableName('second_table_name'); $collection->getSelect()->joinLeft(array('second' => $second_table_name), 'main_table.id = second.customer_id'); return $collection; } } |