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

reeouw's avatar

orderBy relatable table

so I have 2 tables, products and sales.

Product is ABC, and in the sales A = 16, B= 18, C=10.

and I want to show the products ordered by best selling so the order would be like BAC, how to do that?

thank you for your help :)

0 likes
4 replies
burlresearch's avatar

if you only have 2 tables, then what is 'C'?

is everything limited to 2-digits? What if you have more than 99 sales?

this question is flawed - can you be a little more clear?

reeouw's avatar

I mean ABC is the name of products

and the tables are only products and sales, and I just wanna know how to sort by best selling products

vladv's avatar

i think you need to get all sales joined with products (to get the name), grouped by product.id and you need to have a group count as total_sale, then you order by this one desc.

Something like:

Sales::select(\DB::raw('COUNT(sales.id) as total_sales, products.name'))
    ->with('product')
    ->orderBy(\DB::raw('COUNT(sales.id)', 'desc')
    ->groupBy('product.id)
    ->get();

(not tested)

burlresearch's avatar

Another alternative - using Eloquent and collections might go:

Product::has('sales')
    ->get()
    ->sortByDesc(function ($p) {
        return $p->sales->count();
    });

assuming you have your Product model setup correctly with the sales()

Please or to participate in this conversation.