简体   繁体   English

在Magento中获取购物车项目的两个命令之间的差异

[英]Difference between two commands of fetching Shopping Cart Items in Magento

In Magento, if you need to get / fetch the Shopping Cart's Item details, you can do it in any of the two possible ways, which will provide you with all the shopped Items in an array:- 在Magento中,如果您需要获取/获取购物车的项目详细信息,您可以通过两种可能的方式中的任何一种方式进行操作,这将为您提供阵列中所有购物项目: -

  1. $cartItems1 = $cart->getQuote()->getAllItems();
  2. $cartItems2 = $cart->getItems()->getData();

But before using any one of the above two methods, you need to initialize the shopping cart object as:- 但在使用上述两种方法中的任何一种之前,您需要将购物车对象初始化为: -

$cart = new Mage_Checkout_Model_Cart();
$cart->init();

Can anyone please describe in details as to what the two options provide & their differences between each other, along with their possible usage. 任何人都可以详细描述这两个选项提供的内容以及它们之间的差异以及它们的可能用途。

In any more such option is available in Magento, can anyone please highlight it? Magento中有更多此类选项,任何人都可以突出显示它吗?

If you look at the code of the Cart and Quote classes everything will become clear. 如果你看一下Cart和Quote类的代码,一切都会变得清晰。

Here's the code for $cart->getItems(): 这是$ cart-> getItems()的代码:

public function getItems()
{
  return $this->getQuote()->getAllVisibleItems();
}

Plain and simple - it just calls a method of the Quote object. 简单明了 - 它只是调用Quote对象的方法。 So the question now is: What is the difference between getAllVisibleItems() and getAllItems() ? 所以现在的问题是: getAllVisibleItems()getAllItems()之间有什么区别?

Let's look at the code of both methods: 我们来看看这两种方法的代码:

public function getAllItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
        if (!$item->isDeleted()) {
            $items[] =  $item;
        }
    }
    return $items;
}

public function getAllVisibleItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
        if (!$item->isDeleted() && !$item->getParentItemId()) {
            $items[] =  $item;
        }
    }
    return $items;
}

The only difference: getAllVisibleItems() has an additional check for each item: 唯一的区别是: getAllVisibleItems()对每个项目都有一个额外的检查:

!$item->getParentItemId()

which tests if the product has a parent (in other words, it tests if it is a simple product). 它测试产品是否有父母(换句话说,它测试它是否是一个简单的产品)。 So this method's return array will be missing simple products, as opposed to getAllItems() . 所以这个方法的返回数组将缺少简单的产品,而不是getAllItems()

Are there any other ways to retrieve items? 有没有其他方法来检索项目?

One would be to directly get the product collection from the quote object: 一种是直接从引用对象获取产品集合:

$productCollection = $cart->getQuote()->getItemsCollection();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM