Question

I am working in magento 2 project.

I need to load product collection by url_key and specific store id. I tried but I am getting issue in store id. I search in stack but didn't get solution.

My Query :

$url = $store->getStore()->getCurrentUrl();
$url_path = parse_url($url, PHP_URL_PATH);
$url_path_parts = array_filter(explode('/', $url_path));
$currenturl = $url_path_parts[1];
$oRewrite = $objectManager->create("Magento\Catalog\Model\Product")->getCollection();
$oRewrite->addAttributeToFilter('url_key', $currenturl, 'left');
$oRewrite->addAttributeToSelect('entity_id');
$oRewrite->addStoreFilter(0); // I tried to set store id but not worked

If I print query of above query I am getting following query:

SELECT `e`.*, IF(at_url_key.value_id > 0, at_url_key.value, at_url_key_default.value) AS `url_key` FROM `catalog_product_entity` AS `e` LEFT JOIN `catalog_product_entity_varchar` AS `at_url_key_default` ON (`at_url_key_default`.`entity_id` = `e`.`entity_id`) AND (`at_url_key_default`.`attribute_id` = '119') AND `at_url_key_default`.`store_id` = 0 LEFT JOIN `catalog_product_entity_varchar` AS `at_url_key` ON (`at_url_key`.`entity_id` = `e`.`entity_id`) AND (`at_url_key`.`attribute_id` = '119') AND (`at_url_key`.`store_id` = 2) WHERE (IF(at_url_key.value_id > 0, at_url_key.value, at_url_key_default.value) = 'holle-pouchy-apfel-mit-karotte-pastinake-90g')

If I add addAttributeToFilter then in query I am getting Inner Join with store id 0 and Left join with store id 2.

I want to get result from store 0. Is it possible to set store id 0 in all join.

Was it helpful?

Solution

Use below code to load any product by filter url key and store id.

    $storeid = 1;
    $objectManager     = \Magento\Framework\App\ObjectManager::getInstance();

    $collection        = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');

    $productcollection = $collection->addAttributeToSelect('*')
        ->addStoreFilter($storeid)
        ->addAttributeToFilter(
            [
                ['attribute' => 'url_key', 'eq' => 'test112'], // Color filter
            ]
        );

   $productInfo = $productcollection->getData();

OTHER TIPS

addAttributeToFilter('url_key', $currenturl);   
addStoreFilter($storeId);
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top