Laravel Eloquent sort by relation table column

Eager loading uses separate queries so you need join for this:

$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.


edit: as per @alexw comment – you still can include columns from joined tables if you need them. You can add them to select or call addSelect/selectRaw etc.

Leave a Comment