Last active
May 3, 2020 18:24
-
-
Save stemwinder/f48b8b566e955136a06d to your computer and use it in GitHub Desktop.
Eloquent: Order parent results by relationship column
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$products = Shop\Product::join('shop_products_options as po', 'po.product_id', '=', 'products.id') | |
->orderBy('po.pinned', 'desc') | |
->select('products.*') // just to avoid fetching anything from joined table | |
->with('options') // if you need options data anyway | |
->paginate(5); | |
// SELECT clause is there in order to not appending joined columns to your Product model. | |
// Originaly found at: http://stackoverflow.com/questions/23530051/laravel-eloquent-sort-by-relation-table-column |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for your quick response.
I used to have it with leftjoin but the result is the same.
That's what I'm trying to do, sort the Albums by the number of downloads that have their Songs, but with the collections after the query. I tried for hours to try to do it directly with Eloquent but I don't know how to do it.