0

Why is it not possible to call a function like this

$this->getCollection()->getSku();

And it's possible to do it with a foreach like this

foreach($this->getCollection() as $item)
$item -> getSku();
endforeach

For reference ... ( in the block folder )

public function getCollection()
{
    $model = $this->_objectManager->create('Ming\Test\Model\Test');
    $collection = $model->getCollection();

    return $collection;
}
3

Magento "Model Collection" is a collection of model. Model collection extend from php IteratorAggregate, Countable, ArrayInterface SPL interface. Here you can handle complex data. So when you create a collection you cant access like this

$this->getCollection()->getSku();

Because it's a collection of items, That's why you need to access such collection following way


foreach($this->getCollection() as $item) {
    $item -> getSku();
}

Learn more from here

| improve this answer | |
  • Thanks! I'll read it up, Anyway if let's say i am going to place an IF conditions like this. if($this->getCollection()->getSku() == ABC123 ){ } I can't possibly use a foreach statement here. what would you recommend me to do? – ming Apr 6 '16 at 8:16
  • In this case why you create collection? You can do it by model. – Sohel Rana Apr 6 '16 at 8:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.