How to add custom sql query to collection in Magento 2
protected function _prepareCollection()
{
$store = $this->getStore();
$collection = $this->productFactory->create()
->getCollection()
->addAttributeToSelect('sku')
->addAttributeToSelect('name')
->addAttributeToSelect('attribute_set_id')
->addAttributeToSelect('type_id')
->setStore($store);
if ($this->moduleManager->isEnabled('Magento_CatalogInventory')) {
$collection->joinField(
'qty',
'cataloginventory_stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
);
}
if ($store->getId()) {
$collection
->addStoreFilter($store)
->joinAttribute(
'name',
'catalog_product/name',
'entity_id',
null,
'inner',
Store::DEFAULT_STORE_ID
)
->joinAttribute(
'custom_name',
'catalog_product/name',
'entity_id',
null,
'inner',
$store->getId()
)
->joinAttribute(
'status',
'catalog_product/status',
'entity_id',
null,
'inner',
$store->getId()
)
->joinAttribute(
'visibility',
'catalog_product/visibility',
'entity_id',
null,
'inner',
$store->getId()
)
->joinAttribute(
'price',
'catalog_product/price',
'entity_id',
null,
'left',
$store->getId()
);
} else {
$collection
->addAttributeToSelect('price')
->joinAttribute(
'status',
'catalog_product/status',
'entity_id',
null,
'inner'
)
->joinAttribute(
'visibility',
'catalog_product/visibility',
'entity_id',
null,
'inner'
);
}
$collection
->addAttributeToFilter(
'creator_id',
['neq' => null]
)
->joinTable(
$collection->getTable('customer_entity'),
'entity_id = creator_id',
[
'vendor_email' => 'email'
]
);
$subquery = new \Zend_Db_Expr("( SELECT entity_id, SUBSTRING_INDEX(value, ',', 1) AS num1 FROM catalog_product_entity_varchar where catalog_product_entity_varchar.attribute_id = 200
UNION DISTINCT
SELECT entity_id, SUBSTRING_INDEX(value, ',', -1) FROM catalog_product_entity_varchar where catalog_product_entity_varchar.attribute_id = 200
)");
$collection->getSelect()->joinInner(
array('vtable' => $subquery),
'vtable.entity_id = `e`.`entity_id`',
[
"vendorId" => "CONCAT(`e`.`entity_id`, '_', vtable.num1)"
]
);
$this->setCollection($collection);
$this->getCollection()->addWebsiteNamesToResult();
return parent::_prepareCollection();
}
Happy Coding…