1

I have 2 ways to fetch a model object:

$orderId = 18;
/** @var \Magento\Sales\Model\Order $firstOrder */
$firstOrder = $this->_orderFactory->create()->load( $orderId);

/** @var \Magento\Sales\Model\ResourceModel\Order\Collection $orderCollection */
$orderCollection = $this->_orderCollectionFactory->create();
$secondOrder = $orderCollection->addFieldToFilter('entity_id', $orderId)->getFirstItem();

/** @var \Magento\Sales\Model\ResourceModel\Order\Collection $orderCollection */
$orderCollection = $this->_orderCollectionFactory->create();
$thirdOrder = $orderCollection->addFilter('entity_id', $orderId)->getFirstItem();

The first one is using load() method of model object.

The 2 last one use collection to fetch and then get the first item of those collections.

I know load() is deprecated, but as I can see Magento 2 core modules use it a lot.

Somebody, please tell me what option is better?

And by the way, what is the diffirent between addFilter() and addFieldToFilter().

0

The best practice is to use Service contracts:

http://devdocs.magento.com/guides/v2.1/extension-dev-guide/service-contracts/service-contracts.html

For example:

https://magento.stackexchange.com/a/155341/33057

  • Khoa, Thank you for your answer! Yeah. there is a way using service contracts, but why the core codes of magento 2 aways use load(), filter() and addToFilter() method ? – Toan Tam Aug 6 '17 at 1:11

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.