首先在做magento开发的过程中我们难免会使用数据集合对象,然后在过滤自己想要的数据,那么如果使用magento代码如何进行操作呢?
Magento 1获取数据集合
我们首先使用 Mage::getModel()
这个方法来获取。举例如下:
我们想要获取订单销量的表的所有的数据 ,也就是数据库表(sales_flat_order)的数据结果集,注意这个是个所有的数据的条目集合。
下面的两种都可以获取到都是一样的。
$collection=Mage::getModel('sales/order')->getCollection();
$collection=Mage::getResourceModel('sales/order_collection');
我们通过上面的代码得到了数据集合一般情况下我们在实际开发过程中都是需要过滤的。
$collection->addFieldToFilter('created_at',array('gt'=>Mage::getModel('core/date')->date('Y-m-d H:i:s',strtotime('2020-01-01')))) ->addFieldToFilter('order_pay_status',array(array('eq'=>'-2'),array('null'=>true))) ->addFieldToFilter('status',array('eq'=>'complete')) ->getSelect() ->limit(50);
我们获取到的结果集通过方法addFieldToFilter()
进行过滤的 ,查找日期大于2020-01-01 并且 order_pay_status = -2 或者 order_pay_status 是null的数据,并且状态是complete的并且限制50数据。
我们通过下面代码打印这个语句的Mysql:
print_r($collection->getSelectSql(true));
可以得出mysql如下
SELECT`main_table`.*FROM`sales_flat_order`AS`main_table` WHERE(`created_at`>'2020-01-01')AND(((`order_pay_status`='-2') OR(`order_pay_status`ISNULL)))AND(`status`='complete')LIMIT50
得到了这个数据集合再通过循环获取每条的数据。
foreach($collection as$order){ $order->getCreatedAt(); //下面这个是得到所有的数据,这是个数组 $order->getData(); }
Magento 2获取数据集合
magento获取相对于magento1稍微复杂一些,代码如下。
<?php namespaceSky8g\HelloWorld\Block; classProductsextends\Magento\Framework\View\Element\Template { protected$_orderCollectionFactory; publicfunction__construct( Magento\Framework\App\Action\Context$context, \Magento\Sales\Model\ResourceModel\Order\CollectionFactory$orderCollectionFactory ){ $this->_orderCollectionFactory=$orderCollectionFactory; parent::__construct($context); } publicfunctiongetOrderCollection() { $collection=$this->_orderCollectionFactory->create() ->addFieldToFilter('created_at',array('gt'=>Mage::getModel('core/date')->date('Y-m-d H:i:s',strtotime('2020-01-01')))) ->addFieldToFilter('order_pay_status',array(array('eq'=>'-2'),array('null'=>true))) ->addFieldToFilter('status',array('eq'=>'complete')) ->getSelect() ->limit(50);//如果你愿意,可以添加条件 return$collection; } }
上面得到的结果和Magento1的得到的一样。
总结
如果你对Magento 1特别熟悉,那么Magento2开发不在话下,只是Magento 2代码的耦合性降低了,变得更加松散,这样便于我们程序工程师开发。 希望对你有帮助。
请登录已经激活账号继续浏此文章所有内容!