Skip to content

Instantly share code, notes, and snippets.

@stemwinder
Last active May 3, 2020 18:24
Show Gist options
  • Save stemwinder/f48b8b566e955136a06d to your computer and use it in GitHub Desktop.
Save stemwinder/f48b8b566e955136a06d to your computer and use it in GitHub Desktop.
Eloquent: Order parent results by relationship column
<?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
@mreduar
Copy link

mreduar commented May 3, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment