Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bencounsell's avatar

Order By hasMany relationship's first entry

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.

0 likes
0 replies

Please or to participate in this conversation.