1717use Magento \Framework \Api \ImageContentValidatorInterface ;
1818use Magento \Framework \Api \ImageProcessorInterface ;
1919use Magento \Framework \Api \SearchCriteria \CollectionProcessorInterface ;
20+ use Magento \Framework \Api \SearchCriteriaInterface ;
2021use Magento \Framework \DB \Adapter \ConnectionException ;
2122use Magento \Framework \DB \Adapter \DeadlockException ;
2223use Magento \Framework \DB \Adapter \LockWaitException ;
@@ -619,7 +620,7 @@ public function deleteById($sku)
619620 /**
620621 * @inheritdoc
621622 */
622- public function getList (\ Magento \ Framework \ Api \ SearchCriteriaInterface $ searchCriteria )
623+ public function getList (SearchCriteriaInterface $ searchCriteria )
623624 {
624625 /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
625626 $ collection = $ this ->collectionFactory ->create ();
@@ -628,6 +629,7 @@ public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCr
628629 $ collection ->addAttributeToSelect ('* ' );
629630 $ collection ->joinAttribute ('status ' , 'catalog_product/status ' , 'entity_id ' , null , 'inner ' );
630631 $ collection ->joinAttribute ('visibility ' , 'catalog_product/visibility ' , 'entity_id ' , null , 'inner ' );
632+ $ this ->joinPositionField ($ collection , $ searchCriteria );
631633
632634 $ this ->collectionProcessor ->process ($ searchCriteria , $ collection );
633635
@@ -856,4 +858,36 @@ private function saveProduct($product): void
856858 );
857859 }
858860 }
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+ }
859893}
0 commit comments