How to get credit memo collection from last 2 weeks in magento2
-
06-10-2020 - |
Question
I see that Magento\Sales\Model\Order\CreditmemoFactory
has createByOrder and createByInvoice methods and I cannot do ->create()->addAttributeToFilter('created_at'
I would like to get the credit memos from the last 2 weeks regardless of when the order was placed. So I cannot do $order->getCreditmemosCollection()
.
Any ideas?
Thanks!
Solution
If I'm understanding your question correctly, you want to load all credit memos created in the last 2 weeks, regardless of when the order was created. Have you looked at using the service contracts for loading your data?
You'd need to inject the following 2 classes into your constructor. The SearchCriteriaBuilder
class for creating the search criteria (filter), and the CreditmemoRepositoryInterface
for loading the credit memos.
\Magento\Sales\Api\CreditmemoRepositoryInterface
\Magento\Framework\Api\SearchCriteriaBuilder
Build up your search criteria:
$yourDate = '2017-01-01';
$searchCriteria = $this->searchCriteriaBuilder
->addFilter(
'created_at',
$yourDate,
'gt'
)->create()
;
Then get the credit memos from the repository:
$creditmemos = $this->creditmemoRepository
->getList($searchCriteria)
->getItems()
;
From there you should be able to loop through the array, loading whatever data it is that you need:
foreach ($creditmemos as $creditmemo) {
echo $creditmemo->getAdjustment();
}
You can see the available methods to call on the $creditmemo
in the class \Magento\Sales\Api\Data\CreditmemoInterface
.
OTHER TIPS
You can include only \Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection
in your constructor, in this case, you can use directly "addFieldToFilter" function without declaring or include searchCriteria
Your construct
public function __construct(
...
\Magento\Sales\Model\ResourceModel\Order\Creditmemo\Collection $creditmemoCollection,
...
) {
...
$this->creditmemoCollection = $creditmemoCollection;
...
}
And your function
public function yourfunction() {
...
$collection = $this->creditmemoCollection;
$collection->addFieldToFilter('created_at', array('gt' => $yourdate));
foreach($collection as $creditmemo):
...
$data = $creditmemo->getData();
....
endforeach;
}