Answers.Body: <p>Here is a simple start. It builds a query, which goes into the commerce lineitems table, groups the rows by purchasableId and gives the top 20 counts. Be aware, that the result consists of Variants-IDs.</p>
  <pre class="lang-php prettyprint-override"><code>        $result = (new Query())-&gt;select([
              'purchasableId',
              'COUNT(purchasableId) as times_bought',
          ])
              -&gt;from(['{{%commerce_lineitems}}'])
              -&gt;orderBy(['times_bought' =&gt; SORT_DESC])
              -&gt;groupBy('purchasableId')
              -&gt;limit(20)
              -&gt;all();
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2022-11-09T21:01:16.123Z
Answers.LastActivityDate: 2022-11-09T21:13:04.013Z
Answers.LastEditDate: 2022-11-09T21:13:04.013Z
Answers.UserDisplayName: Volker Andres
Body: <p>I am currently working on a project where I have to sort products based on their times being sold.
  Unfortunately I could not find anything related to this functionality.</p>
  <p>Where do I start to implement this feature/functionality?</p>
  
Tags: <plugin-craftcommerce><sorting><custom><products>
Title: CraftCMS Commerce order by most sold products
ThreadText: # CraftCMS Commerce order by most sold products
  
  (Asked by: username_0 on 2022-05-18)
  
  I am currently working on a project where I have to sort products based on their times being sold.
  Unfortunately I could not find anything related to this functionality.
  
  Where do I start to implement this feature/functionality?
  
  **Tags:** plugin-craftcommerce, sorting, custom, products
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2022-11-09. Score: 2
  
  Here is a simple start. It builds a query, which goes into the commerce lineitems table, groups the rows by purchasableId and gives the top 20 counts. Be aware, that the result consists of Variants-IDs.
  
  ```php
          $result = (new Query())->select([
              'purchasableId',
              'COUNT(purchasableId) as times_bought',
          ])
              ->from(['{{%commerce_lineitems}}'])
              ->orderBy(['times_bought' => SORT_DESC])
              ->groupBy('purchasableId')
              ->limit(20)
              ->all();
  
  ```
  
  
  ---
  
  