title: Yii2: select last record from a hasMany relation
body: <p>my knowledge on mysql is very basic and now im facing a "complex" (for me) query in which im stuck so thank you in advance if someone could give me some light on this.</p>
  
  <p>I have three tables:</p>
  
  <p><strong>Orders</strong></p>
  
  <pre><code>id | name | comments | ...
  </code></pre>
  
  <p><strong>OrderLines</strong></p>
  
  <pre><code>id | name | sDate | eDate | comments | ...
  </code></pre>
  
  <p><strong>OrderLinesStats</strong></p>
  
  <pre><code>id | lineID | date | status | ...
  </code></pre>
  
  <p>Every day OrderLinesStats is updated via a cron job and gets a new record with actual date, status and other fields so the highest id is the actual data.</p>
  
  <p>Im trying to get that last stats row with a relation in yii2 as follows:</p>
  
  <p><strong>in OrdersLines model:</strong></p>
  
  <pre><code>public function getLastOrdersLinesStats()
  {
      return $this-&gt;hasMany(OrdersLinesStats::className(), ['lineID' =&gt; 'id'])
          -&gt;orderBy(['id'=&gt;SORT_DESC])
          -&gt;groupBy('lineID');
  }
  </code></pre>
  
  <p><strong>OrdersModel:</strong></p>
  
  <pre><code>public function getOrdersLines()
      {
          return $this
              -&gt;hasMany(OrdersLines::className(), ['orderID' =&gt; 'id'])
              -&gt;orderBy(['typeID' =&gt; SORT_ASC, 'name' =&gt; SORT_ASC])
              -&gt;with(['lastOrdersLinesStats']);
      }
  </code></pre>
  
  <p>But when I debug the query looks like this:</p>
  
  <pre><code>SELECT * FROM `ordersLinesStats` WHERE `lineID` IN (1873, 1872, 1884, 1883, 1870, 1874, 1876, 1880, 1871, 1877, 1881, 1882, 1885, 1886, 1869, 1875, 1878) GROUP BY `lineID` ORDER BY `id` DESC
  </code></pre>
  
  <p>and doesnt give me the last stats record for each line... in fact, it gives me the oldest one. Seems that im missing something but i cant find it.</p>
  
  <p>Thanks again</p>