1

I have the following tables:

PRODUCTS id | title -- | --------------- 1 | First Product 2 | Second Product 3 | Third Product

PRODUCT_VERSIONS id | product_id | release_date -- | ---------- | ------------ 1 | 1 | 2013-01-01 2 | 1 | 2014-01-01 3 | 1 | 2015-03-01 4 | 2 | 2013-02-02 5 | 2 | 2014-02-02 6 | 2 | 2015-02-02 7 | 3 | 2013-03-03 8 | 3 | 2014-03-03 9 | 3 | 2015-03-03


Relationships

Product->hasMany("ProductVersion")

ProductVersion->belongsTo("Product")


What I want to do is select all products and order by the first (oldest) product_version.release_date.

Or maybe it's better to sort the product_versions by release_date, group by addon_id and then join the product table?

I have searched and searched for a solution, and I have a couple queries that almost work. I'm wondering if there is an easy(ish) way of doing this with Laravel.

Bogdan Burym
  • 5,482
  • 2
  • 27
  • 46
  • I think that [this](http://stackoverflow.com/questions/18143061/laravel-orderby-on-a-relationship) may be what you're looking for. Check out the comments to. – Andrei Nov 20 '15 at 14:53
  • Possible duplicate of [Laravel order by hasmany relationship](http://stackoverflow.com/questions/28634921/laravel-order-by-hasmany-relationship) – patricus Nov 20 '15 at 15:12

1 Answers1

0

You can use joins for this. Join the two tables, group them by id, order by the latest date, which I aliased as "latest_release_date":

$products = Product::selectRaw('products.*, MAX(product_versions.release_date) as latest_release_date')
    ->leftJoin('product_versions', 'product_versions.product_id', '=', 'products.id')
    ->orderBy('latest_release_date', 'DESC')
    ->groupBy('products.id')
    ->get();

You mentioned grouping by addon_id, but it's not shown anywhere on your table examples so I just used names from the table examples you provided.

Thomas Kim
  • 15,326
  • 2
  • 52
  • 42