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().

Prince Patel
  • 22,708
  • 10
  • 97
  • 119
Toan Tam
  • 1,318
  • 10
  • 23

1 Answers1

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 TruongDinh
  • 32,054
  • 11
  • 88
  • 155
  • 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 06 '17 at 01:11