Magento 2 : addAttributeToFilter, addAttributeToSelect, addFieldToFilter not working
I created eav entity module. But, when I use this addAttributeToFilter, addAttributeToSelect, addFieldToFilter
function in my custom module collection. It's not working.
My collection file :
I extend MagentoEavModelEntityCollectionAbstractCollection
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorNameModuleNameModelResourceModelMainpage;
use MagentoEavModelConfig;
use MagentoEavModelEntityCollectionAbstractCollection;
use MagentoEavModelEntityFactory as EavEntityFactory;
use MagentoEavModelResourceModelHelper;
use MagentoFrameworkAppResourceConnection;
use MagentoFrameworkDataCollectionDbFetchStrategyInterface;
use MagentoFrameworkDataCollectionEntityFactory;
use MagentoFrameworkDBAdapterAdapterInterface;
use MagentoFrameworkEventManagerInterface;
use MagentoFrameworkValidatorUniversalFactory;
use MagentoStoreModelStoreManagerInterface;
use PsrLogLoggerInterface;
/**
* Class Collection
* @package VendorNameModuleNameModelResourceModelMainpage
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Collection extends AbstractCollection
{
/**
* @var string
*/
protected $_idFieldName = 'entity_id';
/**
* @var $_storeId
*/
protected $_storeId;
/**
* @var StoreManagerInterface
*/
protected $_storeManager;
const KEY_MAIN_VIDEO_TITLE = 'main_video_title';
/**
* @param EntityFactory $entityFactory
* @param LoggerInterface $logger
* @param FetchStrategyInterface $fetchStrategy
* @param ManagerInterface $eventManager
* @param Config $eavConfig
* @param ResourceConnection $resource
* @param EavEntityFactory $eavEntityFactory
* @param Helper $resourceHelper
* @param UniversalFactory $universalFactory
* @param StoreManagerInterface $storeManager
* @param AdapterInterface $connection
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
EntityFactory $entityFactory,
LoggerInterface $logger,
FetchStrategyInterface $fetchStrategy,
ManagerInterface $eventManager,
Config $eavConfig,
ResourceConnection $resource,
EavEntityFactory $eavEntityFactory,
Helper $resourceHelper,
UniversalFactory $universalFactory,
StoreManagerInterface $storeManager,
AdapterInterface $connection = null
) {
$this->_storeManager = $storeManager;
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$eavConfig,
$resource,
$eavEntityFactory,
$resourceHelper,
$universalFactory,
$connection
);
}
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(VendorNameModuleNameModelMainpage::class, VendorNameModuleNameModelResourceModelMainpage::class);
}
/**
* Set store scope
*
* @param int|string|MagentoStoreModelStore $store
* @return $this
*/
public function setStore($store)
{
$this->setStoreId($this->_storeManager->getStore($store)->getId());
return $this;
}
/**
* Set store scope
*
* @param int|string|MagentoStoreApiDataStoreInterface $storeId
* @return $this
*/
public function setStoreId($storeId)
{
if ($storeId instanceof MagentoStoreApiDataStoreInterface) {
$storeId = $storeId->getId();
}
$this->_storeId = (int)$storeId;
return $this;
}
/**
* Return current store id
*
* @return int
*/
public function getStoreId()
{
if ($this->_storeId === null) {
$this->setStoreId($this->_storeManager->getStore()->getId());
}
return $this->_storeId;
}
/**
* Retrieve default store id
*
* @return int
*/
public function getDefaultStoreId()
{
return MagentoStoreModelStore::DEFAULT_STORE_ID;
}
/**
* Set main video title
*
* @param int $mainvideoTitle
* @return $this
*/
public function setMainVideoTitle($mainvideoTitle)
{
return $this->setData(self::KEY_MAIN_VIDEO_TITLE, $mainvideoTitle);
}
/**
* {@inheritdoc}
*/
public function getMainVideoTitle()
{
return $this->getData(self::KEY_MAIN_VIDEO_TITLE);
}
/**
* Retrieve attributes load select
*
* @param string $table
* @param array|int $attributeIds
* @return MagentoEavModelEntityCollectionAbstractCollection
*/
protected function _getLoadAttributesSelect($table, $attributeIds = )
{
if (empty($attributeIds)) {
$attributeIds = $this->_selectAttributes;
}
$storeId = $this->getStoreId();
$connection = $this->getConnection();
$entityTable = $this->getEntity()->getEntityTable();
$indexList = $connection->getIndexList($entityTable);
$entityIdField = $indexList[$connection->getPrimaryKeyName($entityTable)]['COLUMNS_LIST'][0];
if ($storeId) {
$joinCondition = [
't_s.attribute_id = t_d.attribute_id',
"t_s.{$entityIdField} = t_d.{$entityIdField}",
$connection->quoteInto('t_s.store_id = ?', $storeId),
];
$select = $connection->select()->from(
['t_d' => $table],
['attribute_id']
)->join(
['e' => $entityTable],
"e.{$entityIdField} = t_d.{$entityIdField}",
['e.entity_id']
)->where(
"e.entity_id IN (?)",
array_keys($this->_itemsById)
)->where(
't_d.attribute_id IN (?)',
$attributeIds
)->joinLeft(
['t_s' => $table],
implode(' AND ', $joinCondition),
)->where(
't_d.store_id = ?',
$connection->getIfNullSql('t_s.store_id', MagentoStoreModelStore::DEFAULT_STORE_ID)
);
} else {
$select = $connection->select()->from(
['t_d' => $table],
['attribute_id']
)->join(
['e' => $entityTable],
"e.{$entityIdField} = t_d.{$entityIdField}",
['e.entity_id']
)->where(
"e.entity_id IN (?)",
array_keys($this->_itemsById)
)->where(
'attribute_id IN (?)',
$attributeIds
)->where(
'store_id = ?',
$this->getDefaultStoreId()
);
}
return $select;
}
/**
* @param MagentoFrameworkDBSelect $select
* @param string $table
* @param string $type
* @return MagentoFrameworkDBSelect
*/
protected function _addLoadAttributesSelectValues($select, $table, $type)
{
$storeId = $this->getStoreId();
if ($storeId) {
$connection = $this->getConnection();
$valueExpr = $connection->getCheckSql('t_s.value_id IS NULL', 't_d.value', 't_s.value');
$select->columns(
['default_value' => 't_d.value', 'store_value' => 't_s.value', 'value' => $valueExpr]
);
} else {
$select = parent::_addLoadAttributesSelectValues($select, $table, $type);
}
return $select;
}
/**
* Adding join statement to collection select instance
*
* @param string $method
* @param object $attribute
* @param string $tableAlias
* @param array $condition
* @param string $fieldCode
* @param string $fieldAlias
* @return MagentoEavModelEntityCollectionAbstractCollection
*/
protected function _joinAttributeToSelect($method, $attribute, $tableAlias, $condition, $fieldCode, $fieldAlias)
{
if (isset($this->_joinAttributes[$fieldCode]['store_id'])) {
$storeId = $this->_joinAttributes[$fieldCode]['store_id'];
} else {
$storeId = $this->getStoreId();
}
$connection = $this->getConnection();
if ($storeId != $this->getDefaultStoreId() && !$attribute->isScopeGlobal()) {
$defCondition = '(' . implode(') AND (', $condition) . ')';
$defAlias = $tableAlias . '_default';
$defAlias = $this->getConnection()->getTableName($defAlias);
$defFieldAlias = str_replace($tableAlias, $defAlias, $fieldAlias);
$tableAlias = $this->getConnection()->getTableName($tableAlias);
$defCondition = str_replace($tableAlias, $defAlias, $defCondition);
$defCondition .= $connection->quoteInto(
" AND " . $connection->quoteColumnAs("{$defAlias}.store_id", null) . " = ?",
$this->getDefaultStoreId()
);
$this->getSelect()->{$method}(
[$defAlias => $attribute->getBackend()->getTable()],
$defCondition,
);
$method = 'joinLeft';
$fieldAlias = $this->getConnection()->getCheckSql(
"{$tableAlias}.value_id > 0",
$fieldAlias,
$defFieldAlias
);
$this->_joinAttributes[$fieldCode]['condition_alias'] = $fieldAlias;
$this->_joinAttributes[$fieldCode]['attribute'] = $attribute;
} else {
$storeId = $this->getDefaultStoreId();
}
$condition = $connection->quoteInto(
$connection->quoteColumnAs("{$tableAlias}.store_id", null) . ' = ?',
$storeId
);
return parent::_joinAttributeToSelect($method, $attribute, $tableAlias, $condition, $fieldCode, $fieldAlias);
}
}
How to do that, this all function should be working as like working in product collection and all.
My code :
<?php
namespace VendorNameModuleNameControllerIndex;
class Index extends MagentoFrameworkAppActionAction
{
/**
* @var MagentoFrameworkViewResultPageFactory
*/
protected $resultPageFactory;
protected $_collectionFactory;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkViewResultPageFactory $resultPageFactory,
VendorNameModuleNameModelResourceModelMainpageCollectionFactory $collectionFactory,
)
{
$this->_collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Default customer account page
*
* @return void
*/
public function execute()
{
$collection = $this->_collectionFactory->create();
$collection->addAttributeToFilter('main_video_title','Main Page Title German'); //main_video_title is my attribute
print_r($collection->getData());
}
}
?>
magento2 collection eav eav-attributes
add a comment |
I created eav entity module. But, when I use this addAttributeToFilter, addAttributeToSelect, addFieldToFilter
function in my custom module collection. It's not working.
My collection file :
I extend MagentoEavModelEntityCollectionAbstractCollection
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorNameModuleNameModelResourceModelMainpage;
use MagentoEavModelConfig;
use MagentoEavModelEntityCollectionAbstractCollection;
use MagentoEavModelEntityFactory as EavEntityFactory;
use MagentoEavModelResourceModelHelper;
use MagentoFrameworkAppResourceConnection;
use MagentoFrameworkDataCollectionDbFetchStrategyInterface;
use MagentoFrameworkDataCollectionEntityFactory;
use MagentoFrameworkDBAdapterAdapterInterface;
use MagentoFrameworkEventManagerInterface;
use MagentoFrameworkValidatorUniversalFactory;
use MagentoStoreModelStoreManagerInterface;
use PsrLogLoggerInterface;
/**
* Class Collection
* @package VendorNameModuleNameModelResourceModelMainpage
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Collection extends AbstractCollection
{
/**
* @var string
*/
protected $_idFieldName = 'entity_id';
/**
* @var $_storeId
*/
protected $_storeId;
/**
* @var StoreManagerInterface
*/
protected $_storeManager;
const KEY_MAIN_VIDEO_TITLE = 'main_video_title';
/**
* @param EntityFactory $entityFactory
* @param LoggerInterface $logger
* @param FetchStrategyInterface $fetchStrategy
* @param ManagerInterface $eventManager
* @param Config $eavConfig
* @param ResourceConnection $resource
* @param EavEntityFactory $eavEntityFactory
* @param Helper $resourceHelper
* @param UniversalFactory $universalFactory
* @param StoreManagerInterface $storeManager
* @param AdapterInterface $connection
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
EntityFactory $entityFactory,
LoggerInterface $logger,
FetchStrategyInterface $fetchStrategy,
ManagerInterface $eventManager,
Config $eavConfig,
ResourceConnection $resource,
EavEntityFactory $eavEntityFactory,
Helper $resourceHelper,
UniversalFactory $universalFactory,
StoreManagerInterface $storeManager,
AdapterInterface $connection = null
) {
$this->_storeManager = $storeManager;
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$eavConfig,
$resource,
$eavEntityFactory,
$resourceHelper,
$universalFactory,
$connection
);
}
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(VendorNameModuleNameModelMainpage::class, VendorNameModuleNameModelResourceModelMainpage::class);
}
/**
* Set store scope
*
* @param int|string|MagentoStoreModelStore $store
* @return $this
*/
public function setStore($store)
{
$this->setStoreId($this->_storeManager->getStore($store)->getId());
return $this;
}
/**
* Set store scope
*
* @param int|string|MagentoStoreApiDataStoreInterface $storeId
* @return $this
*/
public function setStoreId($storeId)
{
if ($storeId instanceof MagentoStoreApiDataStoreInterface) {
$storeId = $storeId->getId();
}
$this->_storeId = (int)$storeId;
return $this;
}
/**
* Return current store id
*
* @return int
*/
public function getStoreId()
{
if ($this->_storeId === null) {
$this->setStoreId($this->_storeManager->getStore()->getId());
}
return $this->_storeId;
}
/**
* Retrieve default store id
*
* @return int
*/
public function getDefaultStoreId()
{
return MagentoStoreModelStore::DEFAULT_STORE_ID;
}
/**
* Set main video title
*
* @param int $mainvideoTitle
* @return $this
*/
public function setMainVideoTitle($mainvideoTitle)
{
return $this->setData(self::KEY_MAIN_VIDEO_TITLE, $mainvideoTitle);
}
/**
* {@inheritdoc}
*/
public function getMainVideoTitle()
{
return $this->getData(self::KEY_MAIN_VIDEO_TITLE);
}
/**
* Retrieve attributes load select
*
* @param string $table
* @param array|int $attributeIds
* @return MagentoEavModelEntityCollectionAbstractCollection
*/
protected function _getLoadAttributesSelect($table, $attributeIds = )
{
if (empty($attributeIds)) {
$attributeIds = $this->_selectAttributes;
}
$storeId = $this->getStoreId();
$connection = $this->getConnection();
$entityTable = $this->getEntity()->getEntityTable();
$indexList = $connection->getIndexList($entityTable);
$entityIdField = $indexList[$connection->getPrimaryKeyName($entityTable)]['COLUMNS_LIST'][0];
if ($storeId) {
$joinCondition = [
't_s.attribute_id = t_d.attribute_id',
"t_s.{$entityIdField} = t_d.{$entityIdField}",
$connection->quoteInto('t_s.store_id = ?', $storeId),
];
$select = $connection->select()->from(
['t_d' => $table],
['attribute_id']
)->join(
['e' => $entityTable],
"e.{$entityIdField} = t_d.{$entityIdField}",
['e.entity_id']
)->where(
"e.entity_id IN (?)",
array_keys($this->_itemsById)
)->where(
't_d.attribute_id IN (?)',
$attributeIds
)->joinLeft(
['t_s' => $table],
implode(' AND ', $joinCondition),
)->where(
't_d.store_id = ?',
$connection->getIfNullSql('t_s.store_id', MagentoStoreModelStore::DEFAULT_STORE_ID)
);
} else {
$select = $connection->select()->from(
['t_d' => $table],
['attribute_id']
)->join(
['e' => $entityTable],
"e.{$entityIdField} = t_d.{$entityIdField}",
['e.entity_id']
)->where(
"e.entity_id IN (?)",
array_keys($this->_itemsById)
)->where(
'attribute_id IN (?)',
$attributeIds
)->where(
'store_id = ?',
$this->getDefaultStoreId()
);
}
return $select;
}
/**
* @param MagentoFrameworkDBSelect $select
* @param string $table
* @param string $type
* @return MagentoFrameworkDBSelect
*/
protected function _addLoadAttributesSelectValues($select, $table, $type)
{
$storeId = $this->getStoreId();
if ($storeId) {
$connection = $this->getConnection();
$valueExpr = $connection->getCheckSql('t_s.value_id IS NULL', 't_d.value', 't_s.value');
$select->columns(
['default_value' => 't_d.value', 'store_value' => 't_s.value', 'value' => $valueExpr]
);
} else {
$select = parent::_addLoadAttributesSelectValues($select, $table, $type);
}
return $select;
}
/**
* Adding join statement to collection select instance
*
* @param string $method
* @param object $attribute
* @param string $tableAlias
* @param array $condition
* @param string $fieldCode
* @param string $fieldAlias
* @return MagentoEavModelEntityCollectionAbstractCollection
*/
protected function _joinAttributeToSelect($method, $attribute, $tableAlias, $condition, $fieldCode, $fieldAlias)
{
if (isset($this->_joinAttributes[$fieldCode]['store_id'])) {
$storeId = $this->_joinAttributes[$fieldCode]['store_id'];
} else {
$storeId = $this->getStoreId();
}
$connection = $this->getConnection();
if ($storeId != $this->getDefaultStoreId() && !$attribute->isScopeGlobal()) {
$defCondition = '(' . implode(') AND (', $condition) . ')';
$defAlias = $tableAlias . '_default';
$defAlias = $this->getConnection()->getTableName($defAlias);
$defFieldAlias = str_replace($tableAlias, $defAlias, $fieldAlias);
$tableAlias = $this->getConnection()->getTableName($tableAlias);
$defCondition = str_replace($tableAlias, $defAlias, $defCondition);
$defCondition .= $connection->quoteInto(
" AND " . $connection->quoteColumnAs("{$defAlias}.store_id", null) . " = ?",
$this->getDefaultStoreId()
);
$this->getSelect()->{$method}(
[$defAlias => $attribute->getBackend()->getTable()],
$defCondition,
);
$method = 'joinLeft';
$fieldAlias = $this->getConnection()->getCheckSql(
"{$tableAlias}.value_id > 0",
$fieldAlias,
$defFieldAlias
);
$this->_joinAttributes[$fieldCode]['condition_alias'] = $fieldAlias;
$this->_joinAttributes[$fieldCode]['attribute'] = $attribute;
} else {
$storeId = $this->getDefaultStoreId();
}
$condition = $connection->quoteInto(
$connection->quoteColumnAs("{$tableAlias}.store_id", null) . ' = ?',
$storeId
);
return parent::_joinAttributeToSelect($method, $attribute, $tableAlias, $condition, $fieldCode, $fieldAlias);
}
}
How to do that, this all function should be working as like working in product collection and all.
My code :
<?php
namespace VendorNameModuleNameControllerIndex;
class Index extends MagentoFrameworkAppActionAction
{
/**
* @var MagentoFrameworkViewResultPageFactory
*/
protected $resultPageFactory;
protected $_collectionFactory;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkViewResultPageFactory $resultPageFactory,
VendorNameModuleNameModelResourceModelMainpageCollectionFactory $collectionFactory,
)
{
$this->_collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Default customer account page
*
* @return void
*/
public function execute()
{
$collection = $this->_collectionFactory->create();
$collection->addAttributeToFilter('main_video_title','Main Page Title German'); //main_video_title is my attribute
print_r($collection->getData());
}
}
?>
magento2 collection eav eav-attributes
add a comment |
I created eav entity module. But, when I use this addAttributeToFilter, addAttributeToSelect, addFieldToFilter
function in my custom module collection. It's not working.
My collection file :
I extend MagentoEavModelEntityCollectionAbstractCollection
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorNameModuleNameModelResourceModelMainpage;
use MagentoEavModelConfig;
use MagentoEavModelEntityCollectionAbstractCollection;
use MagentoEavModelEntityFactory as EavEntityFactory;
use MagentoEavModelResourceModelHelper;
use MagentoFrameworkAppResourceConnection;
use MagentoFrameworkDataCollectionDbFetchStrategyInterface;
use MagentoFrameworkDataCollectionEntityFactory;
use MagentoFrameworkDBAdapterAdapterInterface;
use MagentoFrameworkEventManagerInterface;
use MagentoFrameworkValidatorUniversalFactory;
use MagentoStoreModelStoreManagerInterface;
use PsrLogLoggerInterface;
/**
* Class Collection
* @package VendorNameModuleNameModelResourceModelMainpage
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Collection extends AbstractCollection
{
/**
* @var string
*/
protected $_idFieldName = 'entity_id';
/**
* @var $_storeId
*/
protected $_storeId;
/**
* @var StoreManagerInterface
*/
protected $_storeManager;
const KEY_MAIN_VIDEO_TITLE = 'main_video_title';
/**
* @param EntityFactory $entityFactory
* @param LoggerInterface $logger
* @param FetchStrategyInterface $fetchStrategy
* @param ManagerInterface $eventManager
* @param Config $eavConfig
* @param ResourceConnection $resource
* @param EavEntityFactory $eavEntityFactory
* @param Helper $resourceHelper
* @param UniversalFactory $universalFactory
* @param StoreManagerInterface $storeManager
* @param AdapterInterface $connection
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
EntityFactory $entityFactory,
LoggerInterface $logger,
FetchStrategyInterface $fetchStrategy,
ManagerInterface $eventManager,
Config $eavConfig,
ResourceConnection $resource,
EavEntityFactory $eavEntityFactory,
Helper $resourceHelper,
UniversalFactory $universalFactory,
StoreManagerInterface $storeManager,
AdapterInterface $connection = null
) {
$this->_storeManager = $storeManager;
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$eavConfig,
$resource,
$eavEntityFactory,
$resourceHelper,
$universalFactory,
$connection
);
}
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(VendorNameModuleNameModelMainpage::class, VendorNameModuleNameModelResourceModelMainpage::class);
}
/**
* Set store scope
*
* @param int|string|MagentoStoreModelStore $store
* @return $this
*/
public function setStore($store)
{
$this->setStoreId($this->_storeManager->getStore($store)->getId());
return $this;
}
/**
* Set store scope
*
* @param int|string|MagentoStoreApiDataStoreInterface $storeId
* @return $this
*/
public function setStoreId($storeId)
{
if ($storeId instanceof MagentoStoreApiDataStoreInterface) {
$storeId = $storeId->getId();
}
$this->_storeId = (int)$storeId;
return $this;
}
/**
* Return current store id
*
* @return int
*/
public function getStoreId()
{
if ($this->_storeId === null) {
$this->setStoreId($this->_storeManager->getStore()->getId());
}
return $this->_storeId;
}
/**
* Retrieve default store id
*
* @return int
*/
public function getDefaultStoreId()
{
return MagentoStoreModelStore::DEFAULT_STORE_ID;
}
/**
* Set main video title
*
* @param int $mainvideoTitle
* @return $this
*/
public function setMainVideoTitle($mainvideoTitle)
{
return $this->setData(self::KEY_MAIN_VIDEO_TITLE, $mainvideoTitle);
}
/**
* {@inheritdoc}
*/
public function getMainVideoTitle()
{
return $this->getData(self::KEY_MAIN_VIDEO_TITLE);
}
/**
* Retrieve attributes load select
*
* @param string $table
* @param array|int $attributeIds
* @return MagentoEavModelEntityCollectionAbstractCollection
*/
protected function _getLoadAttributesSelect($table, $attributeIds = )
{
if (empty($attributeIds)) {
$attributeIds = $this->_selectAttributes;
}
$storeId = $this->getStoreId();
$connection = $this->getConnection();
$entityTable = $this->getEntity()->getEntityTable();
$indexList = $connection->getIndexList($entityTable);
$entityIdField = $indexList[$connection->getPrimaryKeyName($entityTable)]['COLUMNS_LIST'][0];
if ($storeId) {
$joinCondition = [
't_s.attribute_id = t_d.attribute_id',
"t_s.{$entityIdField} = t_d.{$entityIdField}",
$connection->quoteInto('t_s.store_id = ?', $storeId),
];
$select = $connection->select()->from(
['t_d' => $table],
['attribute_id']
)->join(
['e' => $entityTable],
"e.{$entityIdField} = t_d.{$entityIdField}",
['e.entity_id']
)->where(
"e.entity_id IN (?)",
array_keys($this->_itemsById)
)->where(
't_d.attribute_id IN (?)',
$attributeIds
)->joinLeft(
['t_s' => $table],
implode(' AND ', $joinCondition),
)->where(
't_d.store_id = ?',
$connection->getIfNullSql('t_s.store_id', MagentoStoreModelStore::DEFAULT_STORE_ID)
);
} else {
$select = $connection->select()->from(
['t_d' => $table],
['attribute_id']
)->join(
['e' => $entityTable],
"e.{$entityIdField} = t_d.{$entityIdField}",
['e.entity_id']
)->where(
"e.entity_id IN (?)",
array_keys($this->_itemsById)
)->where(
'attribute_id IN (?)',
$attributeIds
)->where(
'store_id = ?',
$this->getDefaultStoreId()
);
}
return $select;
}
/**
* @param MagentoFrameworkDBSelect $select
* @param string $table
* @param string $type
* @return MagentoFrameworkDBSelect
*/
protected function _addLoadAttributesSelectValues($select, $table, $type)
{
$storeId = $this->getStoreId();
if ($storeId) {
$connection = $this->getConnection();
$valueExpr = $connection->getCheckSql('t_s.value_id IS NULL', 't_d.value', 't_s.value');
$select->columns(
['default_value' => 't_d.value', 'store_value' => 't_s.value', 'value' => $valueExpr]
);
} else {
$select = parent::_addLoadAttributesSelectValues($select, $table, $type);
}
return $select;
}
/**
* Adding join statement to collection select instance
*
* @param string $method
* @param object $attribute
* @param string $tableAlias
* @param array $condition
* @param string $fieldCode
* @param string $fieldAlias
* @return MagentoEavModelEntityCollectionAbstractCollection
*/
protected function _joinAttributeToSelect($method, $attribute, $tableAlias, $condition, $fieldCode, $fieldAlias)
{
if (isset($this->_joinAttributes[$fieldCode]['store_id'])) {
$storeId = $this->_joinAttributes[$fieldCode]['store_id'];
} else {
$storeId = $this->getStoreId();
}
$connection = $this->getConnection();
if ($storeId != $this->getDefaultStoreId() && !$attribute->isScopeGlobal()) {
$defCondition = '(' . implode(') AND (', $condition) . ')';
$defAlias = $tableAlias . '_default';
$defAlias = $this->getConnection()->getTableName($defAlias);
$defFieldAlias = str_replace($tableAlias, $defAlias, $fieldAlias);
$tableAlias = $this->getConnection()->getTableName($tableAlias);
$defCondition = str_replace($tableAlias, $defAlias, $defCondition);
$defCondition .= $connection->quoteInto(
" AND " . $connection->quoteColumnAs("{$defAlias}.store_id", null) . " = ?",
$this->getDefaultStoreId()
);
$this->getSelect()->{$method}(
[$defAlias => $attribute->getBackend()->getTable()],
$defCondition,
);
$method = 'joinLeft';
$fieldAlias = $this->getConnection()->getCheckSql(
"{$tableAlias}.value_id > 0",
$fieldAlias,
$defFieldAlias
);
$this->_joinAttributes[$fieldCode]['condition_alias'] = $fieldAlias;
$this->_joinAttributes[$fieldCode]['attribute'] = $attribute;
} else {
$storeId = $this->getDefaultStoreId();
}
$condition = $connection->quoteInto(
$connection->quoteColumnAs("{$tableAlias}.store_id", null) . ' = ?',
$storeId
);
return parent::_joinAttributeToSelect($method, $attribute, $tableAlias, $condition, $fieldCode, $fieldAlias);
}
}
How to do that, this all function should be working as like working in product collection and all.
My code :
<?php
namespace VendorNameModuleNameControllerIndex;
class Index extends MagentoFrameworkAppActionAction
{
/**
* @var MagentoFrameworkViewResultPageFactory
*/
protected $resultPageFactory;
protected $_collectionFactory;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkViewResultPageFactory $resultPageFactory,
VendorNameModuleNameModelResourceModelMainpageCollectionFactory $collectionFactory,
)
{
$this->_collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Default customer account page
*
* @return void
*/
public function execute()
{
$collection = $this->_collectionFactory->create();
$collection->addAttributeToFilter('main_video_title','Main Page Title German'); //main_video_title is my attribute
print_r($collection->getData());
}
}
?>
magento2 collection eav eav-attributes
I created eav entity module. But, when I use this addAttributeToFilter, addAttributeToSelect, addFieldToFilter
function in my custom module collection. It's not working.
My collection file :
I extend MagentoEavModelEntityCollectionAbstractCollection
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace VendorNameModuleNameModelResourceModelMainpage;
use MagentoEavModelConfig;
use MagentoEavModelEntityCollectionAbstractCollection;
use MagentoEavModelEntityFactory as EavEntityFactory;
use MagentoEavModelResourceModelHelper;
use MagentoFrameworkAppResourceConnection;
use MagentoFrameworkDataCollectionDbFetchStrategyInterface;
use MagentoFrameworkDataCollectionEntityFactory;
use MagentoFrameworkDBAdapterAdapterInterface;
use MagentoFrameworkEventManagerInterface;
use MagentoFrameworkValidatorUniversalFactory;
use MagentoStoreModelStoreManagerInterface;
use PsrLogLoggerInterface;
/**
* Class Collection
* @package VendorNameModuleNameModelResourceModelMainpage
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Collection extends AbstractCollection
{
/**
* @var string
*/
protected $_idFieldName = 'entity_id';
/**
* @var $_storeId
*/
protected $_storeId;
/**
* @var StoreManagerInterface
*/
protected $_storeManager;
const KEY_MAIN_VIDEO_TITLE = 'main_video_title';
/**
* @param EntityFactory $entityFactory
* @param LoggerInterface $logger
* @param FetchStrategyInterface $fetchStrategy
* @param ManagerInterface $eventManager
* @param Config $eavConfig
* @param ResourceConnection $resource
* @param EavEntityFactory $eavEntityFactory
* @param Helper $resourceHelper
* @param UniversalFactory $universalFactory
* @param StoreManagerInterface $storeManager
* @param AdapterInterface $connection
*
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
EntityFactory $entityFactory,
LoggerInterface $logger,
FetchStrategyInterface $fetchStrategy,
ManagerInterface $eventManager,
Config $eavConfig,
ResourceConnection $resource,
EavEntityFactory $eavEntityFactory,
Helper $resourceHelper,
UniversalFactory $universalFactory,
StoreManagerInterface $storeManager,
AdapterInterface $connection = null
) {
$this->_storeManager = $storeManager;
parent::__construct(
$entityFactory,
$logger,
$fetchStrategy,
$eventManager,
$eavConfig,
$resource,
$eavEntityFactory,
$resourceHelper,
$universalFactory,
$connection
);
}
/**
* Define resource model
*
* @return void
*/
protected function _construct()
{
$this->_init(VendorNameModuleNameModelMainpage::class, VendorNameModuleNameModelResourceModelMainpage::class);
}
/**
* Set store scope
*
* @param int|string|MagentoStoreModelStore $store
* @return $this
*/
public function setStore($store)
{
$this->setStoreId($this->_storeManager->getStore($store)->getId());
return $this;
}
/**
* Set store scope
*
* @param int|string|MagentoStoreApiDataStoreInterface $storeId
* @return $this
*/
public function setStoreId($storeId)
{
if ($storeId instanceof MagentoStoreApiDataStoreInterface) {
$storeId = $storeId->getId();
}
$this->_storeId = (int)$storeId;
return $this;
}
/**
* Return current store id
*
* @return int
*/
public function getStoreId()
{
if ($this->_storeId === null) {
$this->setStoreId($this->_storeManager->getStore()->getId());
}
return $this->_storeId;
}
/**
* Retrieve default store id
*
* @return int
*/
public function getDefaultStoreId()
{
return MagentoStoreModelStore::DEFAULT_STORE_ID;
}
/**
* Set main video title
*
* @param int $mainvideoTitle
* @return $this
*/
public function setMainVideoTitle($mainvideoTitle)
{
return $this->setData(self::KEY_MAIN_VIDEO_TITLE, $mainvideoTitle);
}
/**
* {@inheritdoc}
*/
public function getMainVideoTitle()
{
return $this->getData(self::KEY_MAIN_VIDEO_TITLE);
}
/**
* Retrieve attributes load select
*
* @param string $table
* @param array|int $attributeIds
* @return MagentoEavModelEntityCollectionAbstractCollection
*/
protected function _getLoadAttributesSelect($table, $attributeIds = )
{
if (empty($attributeIds)) {
$attributeIds = $this->_selectAttributes;
}
$storeId = $this->getStoreId();
$connection = $this->getConnection();
$entityTable = $this->getEntity()->getEntityTable();
$indexList = $connection->getIndexList($entityTable);
$entityIdField = $indexList[$connection->getPrimaryKeyName($entityTable)]['COLUMNS_LIST'][0];
if ($storeId) {
$joinCondition = [
't_s.attribute_id = t_d.attribute_id',
"t_s.{$entityIdField} = t_d.{$entityIdField}",
$connection->quoteInto('t_s.store_id = ?', $storeId),
];
$select = $connection->select()->from(
['t_d' => $table],
['attribute_id']
)->join(
['e' => $entityTable],
"e.{$entityIdField} = t_d.{$entityIdField}",
['e.entity_id']
)->where(
"e.entity_id IN (?)",
array_keys($this->_itemsById)
)->where(
't_d.attribute_id IN (?)',
$attributeIds
)->joinLeft(
['t_s' => $table],
implode(' AND ', $joinCondition),
)->where(
't_d.store_id = ?',
$connection->getIfNullSql('t_s.store_id', MagentoStoreModelStore::DEFAULT_STORE_ID)
);
} else {
$select = $connection->select()->from(
['t_d' => $table],
['attribute_id']
)->join(
['e' => $entityTable],
"e.{$entityIdField} = t_d.{$entityIdField}",
['e.entity_id']
)->where(
"e.entity_id IN (?)",
array_keys($this->_itemsById)
)->where(
'attribute_id IN (?)',
$attributeIds
)->where(
'store_id = ?',
$this->getDefaultStoreId()
);
}
return $select;
}
/**
* @param MagentoFrameworkDBSelect $select
* @param string $table
* @param string $type
* @return MagentoFrameworkDBSelect
*/
protected function _addLoadAttributesSelectValues($select, $table, $type)
{
$storeId = $this->getStoreId();
if ($storeId) {
$connection = $this->getConnection();
$valueExpr = $connection->getCheckSql('t_s.value_id IS NULL', 't_d.value', 't_s.value');
$select->columns(
['default_value' => 't_d.value', 'store_value' => 't_s.value', 'value' => $valueExpr]
);
} else {
$select = parent::_addLoadAttributesSelectValues($select, $table, $type);
}
return $select;
}
/**
* Adding join statement to collection select instance
*
* @param string $method
* @param object $attribute
* @param string $tableAlias
* @param array $condition
* @param string $fieldCode
* @param string $fieldAlias
* @return MagentoEavModelEntityCollectionAbstractCollection
*/
protected function _joinAttributeToSelect($method, $attribute, $tableAlias, $condition, $fieldCode, $fieldAlias)
{
if (isset($this->_joinAttributes[$fieldCode]['store_id'])) {
$storeId = $this->_joinAttributes[$fieldCode]['store_id'];
} else {
$storeId = $this->getStoreId();
}
$connection = $this->getConnection();
if ($storeId != $this->getDefaultStoreId() && !$attribute->isScopeGlobal()) {
$defCondition = '(' . implode(') AND (', $condition) . ')';
$defAlias = $tableAlias . '_default';
$defAlias = $this->getConnection()->getTableName($defAlias);
$defFieldAlias = str_replace($tableAlias, $defAlias, $fieldAlias);
$tableAlias = $this->getConnection()->getTableName($tableAlias);
$defCondition = str_replace($tableAlias, $defAlias, $defCondition);
$defCondition .= $connection->quoteInto(
" AND " . $connection->quoteColumnAs("{$defAlias}.store_id", null) . " = ?",
$this->getDefaultStoreId()
);
$this->getSelect()->{$method}(
[$defAlias => $attribute->getBackend()->getTable()],
$defCondition,
);
$method = 'joinLeft';
$fieldAlias = $this->getConnection()->getCheckSql(
"{$tableAlias}.value_id > 0",
$fieldAlias,
$defFieldAlias
);
$this->_joinAttributes[$fieldCode]['condition_alias'] = $fieldAlias;
$this->_joinAttributes[$fieldCode]['attribute'] = $attribute;
} else {
$storeId = $this->getDefaultStoreId();
}
$condition = $connection->quoteInto(
$connection->quoteColumnAs("{$tableAlias}.store_id", null) . ' = ?',
$storeId
);
return parent::_joinAttributeToSelect($method, $attribute, $tableAlias, $condition, $fieldCode, $fieldAlias);
}
}
How to do that, this all function should be working as like working in product collection and all.
My code :
<?php
namespace VendorNameModuleNameControllerIndex;
class Index extends MagentoFrameworkAppActionAction
{
/**
* @var MagentoFrameworkViewResultPageFactory
*/
protected $resultPageFactory;
protected $_collectionFactory;
public function __construct(
MagentoFrameworkAppActionContext $context,
MagentoFrameworkViewResultPageFactory $resultPageFactory,
VendorNameModuleNameModelResourceModelMainpageCollectionFactory $collectionFactory,
)
{
$this->_collectionFactory = $collectionFactory;
parent::__construct($context);
}
/**
* Default customer account page
*
* @return void
*/
public function execute()
{
$collection = $this->_collectionFactory->create();
$collection->addAttributeToFilter('main_video_title','Main Page Title German'); //main_video_title is my attribute
print_r($collection->getData());
}
}
?>
magento2 collection eav eav-attributes
magento2 collection eav eav-attributes
asked 5 mins ago
Emipro Technologies Pvt. Ltd.Emipro Technologies Pvt. Ltd.
2,5281825
2,5281825
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "479"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f264128%2fmagento-2-addattributetofilter-addattributetoselect-addfieldtofilter-not-wor%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f264128%2fmagento-2-addattributetofilter-addattributetoselect-addfieldtofilter-not-wor%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown