数据库查询-模块-getCollection

一、初始化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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值