Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/sbboke.com/wp-content/plugins/wordpress-seo/src/integrations/front-end-integration.php:409) in /www/wwwroot/sbboke.com/wp-content/themes/pacify/content-single.php on line 5

MAGENTO 2:如何检查产品属性是否存在?

今天,我们的团队需要检查产品自定义属性是否存在。我们希望确保不再尝试创建相同的属性(如果已经存在)。

花了几个小时后,我们找到了最好的方法,并认为我们应该与Magento 2开发人员分享这一点,因为我们相信这也将对其他人有所帮助。

让我们继续看一下代码,以了解如何检查Magento 2中是否存在产品属性

<?php
 
class Custom
{
    /**
     * @var \Magento\Eav\Model\Config
     */
    private $_eavConfig;
 
    /**
     * @param \Magento\Eav\Model\Config $eavConfig
     */
    public function __construct(
        \Magento\Eav\Model\Config $eavConfig
    ) {
        $this->_eavConfig = $eavConfig;
    }
 
    /**
     * Returns true if attribute exists and false if it doesn't exist
     *
     * @param string $field
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function isProductAttributeExists($field)
    {
        $attr = $this->_eavConfig->getAttribute(Product::ENTITY, $field);
 
        return ($attr && $attr->getId()) ? true : false;
    }
}

如您在上面的代码中看到的,\ Magento \ Eav \ Model \ Config类的getAttribute函数可以帮助找出产品属性是否存在。

就是这样,希望本文能以某种方式对您有所帮助。请留下您的评论,让我们知道您的想法?谢谢。

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论