17
17
use Magento \Framework \Api \ImageContentValidatorInterface ;
18
18
use Magento \Framework \Api \ImageProcessorInterface ;
19
19
use Magento \Framework \Api \SearchCriteria \CollectionProcessorInterface ;
20
+ use Magento \Framework \Api \SearchCriteriaInterface ;
20
21
use Magento \Framework \DB \Adapter \ConnectionException ;
21
22
use Magento \Framework \DB \Adapter \DeadlockException ;
22
23
use Magento \Framework \DB \Adapter \LockWaitException ;
@@ -619,7 +620,7 @@ public function deleteById($sku)
619
620
/**
620
621
* @inheritdoc
621
622
*/
622
- public function getList (\ Magento \ Framework \ Api \ SearchCriteriaInterface $ searchCriteria )
623
+ public function getList (SearchCriteriaInterface $ searchCriteria )
623
624
{
624
625
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
625
626
$ collection = $ this ->collectionFactory ->create ();
@@ -628,6 +629,7 @@ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCr
628
629
$ collection ->addAttributeToSelect ('* ' );
629
630
$ collection ->joinAttribute ('status ' , 'catalog_product/status ' , 'entity_id ' , null , 'inner ' );
630
631
$ collection ->joinAttribute ('visibility ' , 'catalog_product/visibility ' , 'entity_id ' , null , 'inner ' );
632
+ $ this ->joinPositionField ($ collection , $ searchCriteria );
631
633
632
634
$ this ->collectionProcessor ->process ($ searchCriteria , $ collection );
633
635
@@ -856,4 +858,36 @@ private function saveProduct($product): void
856
858
);
857
859
}
858
860
}
861
+
862
+ /**
863
+ * Join category position field to make sorting by position possible.
864
+ *
865
+ * @param Collection $collection
866
+ * @param SearchCriteriaInterface $searchCriteria
867
+ * @return void
868
+ */
869
+ private function joinPositionField (
870
+ Collection $ collection ,
871
+ SearchCriteriaInterface $ searchCriteria
872
+ ): void {
873
+ $ categoryIds = [[]];
874
+ foreach ($ searchCriteria ->getFilterGroups () as $ filterGroup ) {
875
+ foreach ($ filterGroup ->getFilters () as $ filter ) {
876
+ if ($ filter ->getField () === 'category_id ' ) {
877
+ $ categoryIds [] = explode (', ' , $ filter ->getValue ());
878
+ }
879
+ }
880
+ }
881
+ $ categoryIds = array_unique (array_merge (...$ categoryIds ));
882
+ if (count ($ categoryIds ) === 1 ) {
883
+ $ collection ->joinField (
884
+ 'position ' ,
885
+ 'catalog_category_product ' ,
886
+ 'position ' ,
887
+ 'product_id=entity_id ' ,
888
+ ['category_id ' => current ($ categoryIds )],
889
+ 'left '
890
+ );
891
+ }
892
+ }
859
893
}
0 commit comments