博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
数据库查询-模块-getCollection
阅读量:7221 次
发布时间:2019-06-29

本文共 4536 字,大约阅读时间需要 15 分钟。

hot3.png

一、初始化Object对象
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();    
//当前店铺
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
var_dump($storeManager->getStore()->getData());
//当前系统时区
$dateObj = $objectManager->get('\Magento\Framework\Stdlib\DateTime\TimezoneInterface'); 
$timezone = $dateObj->getConfigTimezone(); //
Asia/Tokyo
 
一、直接操作数据库
    备注:用以下方式,可以防sql注入
    $query = $this->_connection->select()->from('eav_attribute')->where('attribute_id=?', $attributeId);
    $result = $this->_connection->fetchAll($query);
 
二、日志

\Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface')->addCritical('notice message', ['abc']);

三、判断用户是否已登陆
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if(!$customerSession->isLoggedIn()) {
    //未登陆
}else{
    //已登陆
}
 
四、类目和当前类目产品列表
protected $categoryFactory;
public function __construct (Action\Context $context, \Magento\Catalog\Model\CategoryFactory $categoryFactory) {
$this->categoryFactory = $categoryFactory;
parent::__construct($context);
}
protected function execute() {
//获取分类列表
$categoryCollection = $this->categoryFactory->create()->getCollection();
$categoryCollection->addFieldToSelect(['name']);
$categoryCollection->addAttributeToFilter('level', 2);
$categoryCollection->addAttributeToFilter('is_active', 1); //确保该分类是启用的
$categoryCollection->addAttributeToFilter('include_in_menu', 1);
$categoryCollection->setOrder('position','ASC');
foreach ($categoryCollection as $category){
echo $category->getId();//类目ID
$products = $this->_getProductList($category);//获取当前类目下的产品
}
}
/**获取当前类目下的产品**/
protected function _getProductList ($category) {
$productCollection = $category->getProductCollection();//获取该类目产品
$productCollection->addMinimalPrice()->addUrlRewrite();
$productCollection->addAttributeToSelect(['name', 'small_image',]);
$productCollection->addAttributeToFilter('visibility', array('neq' => 1));// 确保该产品是可见的
$productCollection->addAttributeToFilter('status', 1);// 确保该产品是启用的
$productCollection->setPageSize(20);// 限制该 collection 的结果
$productCollection->setOrder('position','ASC');//排序
//组装数据
$productsArr = [];
foreach ($productCollection as $product){
$data = $product->getData();
$productsArr['products'][] = $data;
}
return $productsArr;
}
 
、获取指定类目的产品

        $category = $this->categoryFactory->create()->load(51);

        //var_dump($category->getId());exit;

        $collection = $this->_productCollectionFactory->create();

        $collection->addAttributeToSelect('*');
        //$collection->addAttributeToFilter('entity_id', 30);
        $collection->addCategoryFilter($category);//获取
        //$collection->setPageSize(3); // fetching only 3 products
        foreach ($collection as $key => $pro) {
            var_dump($pro->getId());
        }

六、获取配置产品下的所有单品

$configProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
if ("configurable" == $configProduct->getTypeId()) {
    //是配置产品
    $_children = $configProduct->getTypeInstance()->getUsedProducts($configProduct);
    foreach ($_children as $child){    
        echo "Single Id: ". $child->getID()."\n";
    }
    echo "count: ".count($_children);
}

七、产品

    1、例子一

    private $productRepository;

    public function __construct(\Magento\Catalog\Model\ProductRepository $productRepository) {

        $this->productRepository = $productRepository;
    }

    public function execute()

    {

        $productId = $this->getRequest()->getParam('product_id');

        $product = $this->productRepository->getById($productId);

         $category_ids = $product->getCategoryIds(); //获取产品类目,array(0=>'2',1=>'10',2=>'20')

    }

    2、例子二

    public function _initProduct()

    {
        $productId = (int)$this->getRequest()->getParam('product');
        if ($productId) {
            $storeId = $this->_objectManager->get(
                \Magento\Store\Model\StoreManagerInterface::class
            )->getStore()->getId();
            try {
                return $this->productRepository->getById($productId, false, $storeId);//
            } catch (NoSuchEntityException $e) {
                return false;
            }
        }
        return false;
    }

    3、例子三

    protected $productFactory;

    public function __construct(
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->productFactory = $productFactory;
    }
    public function render(\Magento\Framework\DataObject $row)
    {

        $product = $this->productFactory->create()->load($row->getProductId());

        return $product->getSku();
    }

    例子4:get product by sku or id

    $productRepository = $this->_objectManager->get('\Magento\Catalog\Model\ProductRepository');

    $product = $productRepository->get($sku);//by sku

    $product = $productRepository->getById($productId);//by id

 

 

 

 

转载于:https://my.oschina.net/ganfanghua/blog/2395404

你可能感兴趣的文章
trick
查看>>
jar包的启动和停止脚本
查看>>
字符串格式化格式 -- Numeric Format Strings
查看>>
arm浮点运算
查看>>
分布式系列 - dubbo服务telnet命令【转】
查看>>
java运维: 一次线上问题排查所引发的思考
查看>>
分布式高并发物联网(车联网-JT808协议)平台架构方案
查看>>
华为S5300系列升级固件S5300SI-V100R006C00SPC800.cc
查看>>
python3.7+opencv3.4.1
查看>>
redux VS mobx (装饰器配合使用)
查看>>
solr 请求参数过长报错,Solr配置maxBooleanClauses属性不生效原因分析
查看>>
【Java】的四种引用的区别
查看>>
SQL Server 如何设置数据库的默认初始大小和自动增长大小
查看>>
cmd.exe启动参数详解
查看>>
Spring 注解<context:annotation-config> 和 <context:component-scan>的作用与区别
查看>>
Perl正则表达式引用
查看>>
混合开发 Hybird Cordova PhoneGap web 跨平台 MD
查看>>
高效沟通的秘籍-沟通视窗
查看>>
Go基础系列:import导包和初始化阶段
查看>>
怎么创建SpringBoot项目
查看>>