0

嗨,我怎样才能在后端检索类别 url 的值?我期望 url 值等于前端中的 url 而不是后端中的 url。有没有办法在 Magento 2 中实现这一点?

4

2 回答 2

0

好的,我找到了答案。解决方案是使用 Magento 中提供的 App/Emulator。这个想法是在执行所需的前端类别 URL 检索之前启动模拟,并在完成后关闭模拟。

以下是有关如何实现它的链接App Emulation。不知道解决问题这么简单。下面是我的代码的样子

class MenuCategory extends \Magento\Framework\Model\AbstractModel implements \Magento\Framework\DataObject\IdentityInterface
{

    public function getStoreCategories($storeManager, $emulator)
    {

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $emulator->startEnvironmentEmulation(null, \Magento\Framework\App\Area::AREA_FRONTEND, true);

        $categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
        $categories = $categoryFactory->create()                              
            ->addAttributeToSelect('*')
            ->setStore($storeManager->getStore())
            ->addAttributeToFilter('level', array('eq' => 2))
            ->addIsActiveFilter()
            ->addAttributeToSort('position', 'asc'); 

        foreach ($categories as $category) {    
            echo $category->getUrl() . " - " . $category->getUrl() . "\n";

        }

        $emulator->stopEnvironmentEmulation();
        return $content;
    }
}

所以这里的想法是实例化模拟器并使magento认为你将像在前端一样修改或执行因此代码\Magento\Framework\App\Area::AREA_FRONTEND当你关闭环境仿真时它会去回到你是在 adminhtml 还是前端

于 2019-02-12T13:59:06.760 回答
-1

为了获取类别 url,您需要使用如下Magento\Catalog\Model\CategoryRepository函数getUrl()

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$emulator->startEnvironmentEmulation(null, \Magento\Framework\App\Area::AREA_FRONTEND, true);

$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()                              
    ->addAttributeToSelect('*')
    ->setStore($storeManager->getStore())
    ->addAttributeToFilter('level', array('eq' => 2))
    ->addIsActiveFilter()
    ->addAttributeToSort('position', 'asc'); 

foreach ($categories as $category) {    
    $categoryObject = $objectManager->create('Magento\Catalog\Model\CategoryRepository')->get($category->getId());
    echo $categoryObject->getUrl()."\n";
}
于 2019-02-12T11:29:25.570 回答