plasmic's avatar

Laravel subquery sorting

Let's say I have two tables, products and product_categories. On the product_categories table, there is id and name. On the products table, there is id, name, and product_category_id.

Now I'd like to sort the products by their category name using a subquery. Here's what I have which is based off an example I found here seems to be working okay but I'm not sure if it's quite right.

... // other logic for initializing the query and filtering

return $query->orderBy(function ($query) {
    $query->select('name')
         ->from('product_categories')
         ->whereColumn('product_category_id', 'product_categories.id')
         ->limit(1);
}, $descending ? 'desc' : 'asc')->paginate(request()->get('perPage', 25));

Also, is this way a better alternative to using a join and sorting by the categories that way?

0 likes
1 reply

Please or to participate in this conversation.